Class: Zerial::ImmutableRecordSerializer

Inherits:
Object
  • Object
show all
Includes:
BaseSerializer
Defined in:
lib/zerial/immutable_record_serializer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from BaseSerializer

#from_json, #to_json

Constructor Details

#initialize(record_class, serializers: {}) ⇒ ImmutableRecordSerializer

Returns a new instance of ImmutableRecordSerializer.



9
10
11
12
# File 'lib/zerial/immutable_record_serializer.rb', line 9

def initialize (record_class, serializers: {})
  @record_class = record_class
  @serializers = serializers
end

Instance Attribute Details

#record_classObject (readonly)

Returns the value of attribute record_class.



7
8
9
# File 'lib/zerial/immutable_record_serializer.rb', line 7

def record_class
  @record_class
end

#serializersObject (readonly)

Returns the value of attribute serializers.



7
8
9
# File 'lib/zerial/immutable_record_serializer.rb', line 7

def serializers
  @serializers
end

Instance Method Details

#as_json(object) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/zerial/immutable_record_serializer.rb', line 14

def as_json (object)
  record_class::ATTRIBUTES.reduce({}) do |attributes, attr|
    attributes.merge(
      attr.to_s => serializer_for_attribute(attr).as_json(
        object.public_send(attr)
      )
    )
  end
end

#from_loaded_json(json) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/zerial/immutable_record_serializer.rb', line 24

def from_loaded_json (json)
  record_class.new(
    record_class::ATTRIBUTES.reduce({}) { |attributes, attr|
      attributes.merge(
        attr => serializer_for_attribute(attr).from_loaded_json(
          json.fetch(attr.to_s)
        )
      )
    }
  )
end