abstract class Serializer::Base(T)
- Serializer::Base(T)
- Serializer::Serializable
- Reference
- Object
Overview
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
Included Modules
Defined in:
serializer/base.crConstructors
Instance Method Summary
-
#serialize_attributes(object, io, except, opts)
Serializes target's attributes to io.
-
#serialize_relations(object, fields_count, io, includes, opts)
Serializes target's relations to io.
Macros inherited from module Serializer::DSL
attribute(name, key = nil, if if_proc = nil)
attribute,
attributes(*names)
attributes,
belongs_to(name, serializer, key = nil)
belongs_to,
has_many(name, serializer, key = nil)
has_many,
has_one(name, serializer, key = nil)
has_one
Instance methods inherited from class Serializer::Serializable
serialize(except : Array(Symbol) = [] of ::Symbol, includes : Array(Symbol) | Hash = [] of ::Symbol, opts : Hash | Nil = nil, meta : Hash(Symbol, MetaAny) | Nil = nil)
serialize,
serialize_attributes(target, io, except, opts)
serialize_attributes,
serialize_relations(target, fields_count, io, includes, opts)
serialize_relations
Constructor Detail
Instance Method Detail
def serialize_attributes(object, io, except, opts)
#
Description copied from class Serializer::Serializable
Serializes target's attributes to io.
def serialize_relations(object, fields_count, io, includes, opts)
#
Description copied from class Serializer::Serializable
Serializes target's relations to io.