Cerializable
Cerializable provides flexible custom serialization for Rails models.
HOW TO USE
Add Cerializable to your Gemfile
gem 'cerializable', git: 'git://github.com/nativestranger/cerializable.git', branch: 'master'
Call ‘acts_as_cerializable’ in the models you wish to use Cerializable with.
class Comment < ApplicationRecord
acts_as_cerializable
end
Define corresponding serializer modules.
module CommentSerializer
include ActionView::Helpers::DateHelper
def run(comment, )
{ id: comment.id,
user: { id: comment.user.id,
name: comment.user.name },
body: comment.body,
ancestorCount: comment.ancestor_count,
childComments: [:children] || comment.child_comments.order(id: :desc).map { |c| c.serializable_hash },
createdAtInWords: "#{ time_ago_in_words(comment.created_at) } ago" }
end
end
The only requirement is that the ‘run’ method accepts two arguments and returns a hash which details how any given instance of your model is to be represented in JSON.
Pass custom options to #as_json, #to_json, or #serializable_hash and your models will use the #run method of their serializers to produce the result.
If you wish, you can specify the serializer module to use:
class Comment < ApplicationRecord
acts_as_cerializable serialize_with: SomeSerializerModule
end
TODO:
-
Support #to_xml