nested serializer?
In the readme the nested example says:
def put_post(post)
put :title, post.title
put :body, post.body
put :author, fullname(post.author.first_name, post.author.last_name)
put :comments, CommentsSerializer.new(post.comments) # <- offending line
end
However, the default Serializer class does not take an initializer argument, so this fails. I can add an initializer and an instance variable, but then I get unexpected results. So how do I do this?
Good catch. It should be CommentsSerializer.new.encode!(post.comments) if you want to nest serializers.
In general I define serializer methods in modules and then just include the needed modules in the serializers that use them. Its then just a put_comment(comment) which is faster.
Your suggestion is what I ended up using, but you end up with the internal representation of the serializer on your JSON if you do it with .new.encode!
On 24 nov. 2014, at 15:24, ahacking [email protected] wrote:
Good catch. It should be CommentsSerializer.new.encode!(post.comments) if you want to nest serializers.
In general I define serializer methods in modules and then just include the needed modules in the serializers that use them. Its then just a put_comment(comment) which is faster.
— Reply to this email directly or view it on GitHub.
Sorry for the late reply it was after midnight here.
It used to be IIRC that oj would look for to_json on any object passed to it but that may have changed or my memory is wrong.
The other option is to call .new.json! explicitly. The fastest option is to compose through ruby modules and just call your own put_* methods as there is less object allocation involved.
I'll take a close look later tonight and update the docs accordingly.
Please let me know if there are any other inconsistencies or suggestions you have.
I'd like to make to_json usable for others as it significantly decreased json rendering overhead in my app.