to_json icon indicating copy to clipboard operation
to_json copied to clipboard

nested serializer?

Open beno opened this issue 11 years ago • 3 comments

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?

beno avatar Nov 24 '14 12:11 beno

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.

ahacking avatar Nov 24 '14 14:11 ahacking

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.

beno avatar Nov 24 '14 14:11 beno

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.

ahacking avatar Nov 24 '14 23:11 ahacking