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