Introducing Serial, a light-weight no-magic serialization library (for Ruby, and Rails)
This post was originally published on the Elabs blog, before Elabs and Varvet joined forces.
Jonas and I created a serialization library recently while working on ProjectPuzzle, it’s named Serial.
Serial will generate a Hash or an Array of hashes from an object of your choosing. It has a very small API surface, and is designed to be easy to reason about. It’s suitable for where you’d use YourModel#as_json, ActiveModel::Serializers, or JBuilder. It could look something like this:
# app/serializers/person_serializer.rb
PersonSerializer = Serial::Serializer.new do |h, person|
h.attribute(:id, person.id)
h.attribute(:name, person.name)
h.attribute(:url, account_person_path(person.account, person))
h.attribute(:assignable, policy(person).assignable?)
h.attribute(:skills, person.skills.map(&:name))
h.map(:groups, person.groups, &GroupSerializer)
end
# app/controllers/api/people_controller.rb
include Serial::RailsHelpers
def index
people = People.all
render json: { people: serialize(people) }
end
You’re very welcome to have a look, you can find it at github.com/elabs/serial, we’d love to hear what you think!
Comments