0

I need to give this object a named root before serving it up, is there a cleaner way of doing this?

get '/api/ducks/:id' do |id|
    content_type :json
    duck = {
        duck: Duck.find(id)
    }
    JSONP duck
end
Zen
  • 7,197
  • 8
  • 35
  • 57
  • 1
    I don't know what you're using server side, but perhaps in your environnement you can have something like https://github.com/rails-api/active_model_serializers – sly7_7 Apr 23 '13 at 07:11

2 Answers2

3

I don't know what orm you are using

Assuming you are using active-record

you can set some where in config which applies globaly

ActiveRecord::Base.include_root_in_json = true

or

Duck.find(id).as_json(:root=>true)

http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html

Check this SO answer too https://stackoverflow.com/a/6515973/518832

For MongoMapper

class Something
  include MongoMapper::Document
  self.include_root_in_json = true
end

and then

JSONP Duck.where(:id=>id).to_json

should work as per this github comment https://github.com/jnunemaker/mongomapper/issues/392

also you would like to check the source how it works just for knowledge

https://github.com/jnunemaker/mongomapper/blob/master/lib/mongo_mapper/plugins/serialization.rb

Community
  • 1
  • 1
Pritesh Jain
  • 9,106
  • 4
  • 37
  • 51
  • I'm using Rails and MongoMapper, so no - not using ActiveRecord. – Zen Apr 23 '13 at 22:29
  • @ZenSavona I have updated my answer for MongoMapper hope that helps – Pritesh Jain Apr 24 '13 at 05:53
  • Thanks for that, upvoted. It still doesn't really do what I need though, as Ember requires a single plural root for the /api/ducks and a single singular root for /api/ducks/:id, where this creates a singular named root for each question, regardless of what query is run (Duck.all or Duck.find) – Zen Apr 24 '13 at 06:43
  • 1
    @ZenSavona have updated my answer with where clause i have not used mongomapper let me know if it works – Pritesh Jain Apr 24 '13 at 08:06
2

The only cleaner way is to remove the unneeded variable:

get '/api/ducks/:id' do |id|
    content_type :json
    JSONP { duck: Duck.find(id) }
end
Tim Dorr
  • 4,861
  • 2
  • 21
  • 24