class

Serializer::Base(T)

Inherits Serializer::DSL < Serializer::Serializable < Reference < Object

Base serialization superclass.

class AddressSerializer < Serializer::Base(Address)
  attributes :street
end

class ChildSerializer < Serializer::Base(Child)
  attribute :age

  has_one :address, AddressSerializer
  has_one :dipper, ChildSerializer
end

class ModelSerializer < Serializer::Base(Model)
  attribute :name
  attribute :own_field

  has_many :children, ChildSerializer

  def own_field
    12
  end
end

ModelSerializer.new(object).serialize(
  except: [:own_field],
  includes: {
    :children => {:address => nil, :dipper => [:address]},
  },
  meta: {:page => 0}
)

Example above produces next output (this one is made to be readable - real one has no newlines and indentations):

{
  "data":{
    "name":"test",
    "children":[
      {
        "age":60,
        "address":null,
        "dipper":{
          "age":20,
          "address":{
            "street":"some street"
          }
        }
      }
    ]
  },
  "meta":{
    "page":0
  }
}

For a details about DSL specification or serialization API see DSL and Serializable.

Inheritance

You can DRY your serializers by inheritance - just add required attributes and/or associations in the subclasses.

class UserSerializer < Serializer::Base(User)
  attributes :name, :age
end

class FullUserSerializer < UserSerializer
  attributes :email, :created_at

  has_many :identities, IdentitySerializer
end

Constructors

new(target : T | Array(T) | Nil)
Source

Instance methods

serialize_attributes(object, io, except, opts)

Serializes target's attributes to io.

Source
serialize_relations(object, fields_count, io, includes, opts)

Serializes target's relations to io.

Source