Class: LedgerSync::Adaptors::Test::LedgerSerializer

Inherits:
LedgerSerializer show all
Defined in:
lib/ledger_sync/adaptors/test/ledger_serializer.rb

Instance Attribute Summary

Attributes inherited from LedgerSerializer

#resource

Instance Method Summary collapse

Methods inherited from LedgerSerializer

attribute, #attribute_value_from_ledger, attributes, id, references_many, references_one

Methods included from Mixins::InferResourceClassMixin

included

Constructor Details

#initialize(resource:) ⇒ LedgerSerializer



11
12
13
# File 'lib/ledger_sync/adaptors/test/ledger_serializer.rb', line 11

def initialize(resource:)
  @resource = resource
end

Instance Method Details

#deserialize(hash:) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/ledger_sync/adaptors/test/ledger_serializer.rb', line 15

def deserialize(hash:)
  deserialized_resource = resource.dup

  hash.each do |key, value|
    key = key.to_s
    next unless deserialized_resource.respond_to?("#{key}=")

    resource_attribute = deserialized_resource.resource_attributes[key.to_sym]
    if resource_attribute&.references_many?
      type = LedgerSerializerType::ReferencesManyType
      resource_class = resource_attribute.type.resource_class
    else
      type = LedgerSerializerType::ValueType
      resource_class = resource.class
    end

    ledger_serializer_attribute = LedgerSerializerAttribute.new(
      id: (key == 'id'),
      ledger_attribute: key,
      resource_attribute: key,
      resource_class: resource_class,
      serializer: self.class,
      type: type
    )

    value = attribute_value_from_ledger(
      hash: hash,
      ledger_serializer_attribute: ledger_serializer_attribute,
      resource: deserialized_resource
    )

    deserialized_resource.assign_attribute(
      ledger_serializer_attribute.resource_attribute_dot_parts.first,
      value
    )
  end

  deserialized_resource
end

#to_ledger_hash(only_changes: false) ⇒ Object



55
56
57
58
59
60
# File 'lib/ledger_sync/adaptors/test/ledger_serializer.rb', line 55

def to_ledger_hash(only_changes: false)
  ret = resource.serializer.serialize[:objects].first.last[:data]
  return ret unless only_changes

  ret.select { |e| resource.changes.keys.include?(e.to_s) }
end