views:

198

answers:

2

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?

A: 

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
marcgg
+2  A: 

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)
ry