An easy way to serialize ruby objects :)
Add this line to your application's Gemfile:
gem 'highlighter'And then execute:
$ bundle install
Or install it yourself as:
$ gem install highlighter
class User
attr_accessor :id, :name, :cars
def initialize(id:, name:, cars:)
@id = id
@name = name
@cars = cars
end
endclass Car
attr_accessor :id, :name, :manufacturer
def initialize(id:, name:, manufacturer:)
@id = id
@name = name
@manufacturer = manufacturer
end
endThen, we should define one serializer for each class:
class CarSerializer
include Highlighter::Serializer
attribute :id
attribute :name
attribute :manufacturer
endclass UserSerializer
include Highlighter::Serializer
attribute :id
attribute :name
attribute :cars, serializer: CarSerializer
endcars = [
Car.new(id: 1, name: 'Polo', manufacturer: 'VW'),
Car.new(id: 2, name: 'Focus', manufacturer: 'Ford')
]
user = User.new(id: 1, name: "Kelly", cars: cars, )Now that we have the instances of cars and user in place we just need to instatiate the serializer and call to_h
UserSerializer.new(user, show_description: false).to_hAnd it will return:
{
id: 1,
name: "Kelly",
cars: [
{ id: 0, manufacturer: 'Polo', name: 'VW' },
{ id: 1, manufacturer: 'Focus', name: 'Ford' },
]
}It also supports lambdas to set serializer on the fly:
class UserSerializer
include Highlighter::Serializer
attribute :id
attribute :name
attribute :cars, serializer: ->(options) { options[:custom_serializer] }
endUserSerializer.new(user, custom_serializer: CarSerializer).to_hRenaming attribute:
class UserSerializer
include Highlighter::Serializer
attribute :id
attribute :name, rename_to: :full_name
end{
id: 1,
full_name: "Kelly"
}Passing a list of fields:
class UserSerializer
include Highlighter::Serializer
attributes :id, :name
end{
id: 1,
name: "Kelly"
}Passing a block:
class UserSerializer
include Highlighter::Serializer
attributes :id, :name
attribute :description do |object|
"My name is #{object.name}"
end
end{
id: 1,
name: "Kelly",
description: "My name is John Wick"
}Hiding field
class UserSerializer
include Highlighter::Serializer
attributes :id, :name
attribute :description, if: ->(_object, options) { option[:show_description] }
end{
id: 1,
name: "Kelly"
}After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and the created tag, and push the .gem file to rubygems.org.
Bug reports and pull requests are welcome on GitHub at https://github.com/CaioPenhalver/highlighter.
The gem is available as open source under the terms of the MIT License.