2

I'm currently in the process of switching from ActiveRecord's as_json to RABL for API generation.

as_json has been rendering timestamps in my models as strings of the format 2012-09-16T22:14:11+00:00. However, when I switched to RABL timestamps started rendering as epoch numbers like 1347926218.084763000 (note these dates are from two different objects and are not supposed to be equal). Is there a way to force the string format?

My .rabl template is pretty simple:

object @person
attributes :id, :created_on, :name

and I get:

{"id":3,"created_on":1347926218.084763000,"name":"fred"}
kevboh
  • 5,207
  • 5
  • 38
  • 54

1 Answers1

4
 object @person
   node(:id){|person|(person.id)}
   node(:created_on){|person|(person.created_on.strftime(%d,%m,%Y)}
   node(:name){|person|(person.name)}
 end

or try

 object @person
   attributes :id, :name
   node(:created_on){|person|(person.created_on.strftime(%d,%m,%Y)}
 end

There are more options for .strftime() you can find on many sites. It must be used on a :date object type. You can customize the date output with it's options. I'm working on custom nodes for some json output and am learning this the hard way!

If you need the the attributes in a certain order I'd use the one with nodes because the attributes seem to 'float to the top' of the json object created.

Debbie
  • 136
  • 1
  • 6
  • Ah, this is cool. I wish it worked out of the box, but this seems like a good replacement. Thanks! – kevboh Nov 11 '12 at 14:48