Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nested serializer? #1

Open
beno opened this issue Nov 24, 2014 · 3 comments
Open

nested serializer? #1

beno opened this issue Nov 24, 2014 · 3 comments

Comments

@beno
Copy link

beno commented Nov 24, 2014

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?

@ahacking
Copy link
Owner

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.

@beno
Copy link
Author

beno commented Nov 24, 2014

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.

@ahacking
Copy link
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants