to_json icon indicating copy to clipboard operation
to_json copied to clipboard

Class Readme Example

Open bizmurr opened this issue 10 years ago • 1 comments

Is your class example in the README missing some things?

# A Post model serializer, using ::ToJson::Serializer inheritance
class PostSerializer < ::ToJson::Serializer
  include PostSerialization

  # override the serialize method and use the ToJson DSL
  # any arguments passed to encode! or json! are passed into serialize
  def serialize(model)
    put_post_nested model
  end
end

# A Post collection serializer using include ToJson::Serialize approach
class PostsSerializer
  include PostSerialization

  def serialize(collection)
    put_posts collection
  end
end

# define a module so we can mixin Post model serialization concerns
anywhere and avoid temporary serializer objects for collection items
module PostSerialization
  include  ::ToJson::Serialize

  # formatting helper
  def fullname(*names)
    names.join(' ')
  end

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

  def put_post_nested(post)
    put :post do
      put_post(post)
    end
  end

  def serialize_posts(posts)
    put :meta do
      put :total_entries, posts.total_entries
      put :total_pages, posts.total_pages
    end
    put :collection, posts do |post|
      put_post post
    end

  end
end

Should PostsSerializer be inheriting from ::ToJson::Serializer?

And is put_posts collection, actually serialize_posts?

bizmurr avatar Mar 07 '15 06:03 bizmurr

Yes, why inherit from ::ToJson::Serializer and include PostSerialization? Are both required?

xtagon avatar Sep 12 '15 05:09 xtagon