Assume we have something like:
class Company
include Mongoid::Document
has_many :users
field :name, type: String
end
class User
include Mongoid::Document
belongs_to :company
field :name, type: String
end
module CompanyRepresenter
include Roar::Representer::JSON
property :name
end
module UserRepresenter
include Roar::Representer::JSON
property :name
link :self do
user_url
end
end
Then we go on to do something like this:
user.extend(UserRepresenter).to_json
And everything is just great. But how about:
User.all.to_json
or:
company.extend(CompanyRepresenter).users.to_json?
or even:
company.users.collect{|u| u.extend(UserRepresenter)}.extend(Representable::JSON::Collection).to_json
The result is always an array of Mongoid's normal to_json
entries.
The question is how do I get something like Company.all.to_json
to have Roared JSONs including the links and other extra serialization data.
It turns out this is simple to achieve using Representable (which is used by Roar):
require 'roar/representer/json'
module PostRepresenter
include Roar::Representer::JSON
property :id
property :title
end
require 'representable/json/collection'
module PostsRepresenter
include Representable::JSON::Collection
items extend: PostRepresenter
end
Post.limit(10).extend(PostsRepresenter)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With