Class: Apiwork::Representation::Serializer

Inherits:
Object
  • Object
show all
Defined in:
lib/apiwork/representation/serializer.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(representation, includes) ⇒ Serializer

Returns a new instance of Serializer.



12
13
14
15
16
# File 'lib/apiwork/representation/serializer.rb', line 12

def initialize(representation, includes)
  @representation = representation
  @representation_class = representation.class
  @includes = includes
end

Class Method Details

.serialize(representation, includes) ⇒ Object



7
8
9
# File 'lib/apiwork/representation/serializer.rb', line 7

def serialize(representation, includes)
  new(representation, includes).serialize
end

Instance Method Details

#serializeObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/apiwork/representation/serializer.rb', line 18

def serialize
  fields = {}

  add_discriminator_field(fields) if @representation_class.subclass?

  @representation_class.attributes.each do |name, attribute|
    next if attribute.write_only?

    value = @representation.respond_to?(name) ? @representation.public_send(name) : @representation.record.public_send(name)
    value = map_type_column_output(name, value)
    value = attribute.encode(value)
    fields[name] = value
  end

  @representation_class.associations.each do |name, association|
    next unless include_association?(name, association)

    fields[name] = serialize_association(name, association)
  end

  fields
end