Reputation: 61
I'm exposing some resources via a simple API that returns JSON. I would like to inject the path to each of the resources so that the consumer need not construct them. Example of desired output for something like User.all.to_json
:
users: [
{user: {
id: 1,
name: 'Zaphod',
url: 'http://domain.com/users/1.json'
}},
{user: {
id: 2,
name: 'Baron Munchausen',
url: 'http://domain.com/users/2.json'
}}
];
In order to generate the URL I'd like to continue using the helpers and not pollute the models with this kind of information. Is there a way to do this? Or am I better off just putting this into the model?
Upvotes: 3
Views: 1105
Reputation: 8055
If you have a model method you want included in the json serialization you can just use the builtin to_json call with the :methods
parameter:
class Range
def url
# generate url
...
end
end
Range.find(:first).to_json(:methods => :url)
Upvotes: 4
Reputation: 66535
Have you checked this out : http://json.rubyforge.org/ ?
class Range
def to_json(*a)
{
'json_class' => self.class.name,
'data' => [ first, last, exclude_end? ]
}.to_json(*a)
end
def self.json_create(o)
new(*o['data'])
end
end
Upvotes: 0