Define an as_json method on your response model. This gets run whenever you return an instance of the response model as JSON to your REST API.
def as_json(options={})
{
:id => self.id,
:created_at => self.created_at.to_time.to_i,
:updated_at => self.updated_at.to_time.to_i
}
end
You can also call the as_json method explicitly to get the hash back and use it elsewhere.
hash = @response.as_json
Unix timestamp reference: Ruby/Rails: converting a Date to a UNIX timestamp
Edit: The as_json method works for relationships as well. Simply add the key to the hash returned by the function. This will run the as_json method of the associated model as well.
def as_json(options={})
{
:id => self.id,
:created_at => self.created_at.to_time.to_i,
:updated_at => self.updated_at.to_time.to_i,
:object2 => self.object2,
:posts => self.posts
}
end
Furthermore, you can pass in parameters to the method to control how the hash is built.
def as_json(options={})
json = {
:id => self.id,
:created_at => self.created_at.to_time.to_i,
:updated_at => self.updated_at.to_time.to_i,
:object2 => self.object2
}
if options[:posts] == true
json[:posts] = self.posts
end
json
end
hash = @response.as_json({:posts => true})