Class: LedgerSync::Serialization::SerializerAttribute

Inherits:
Attribute
  • Object
show all
Defined in:
lib/ledger_sync/serialization/serializer_attribute.rb

Instance Attribute Summary

Attributes inherited from Attribute

#block, #hash_attribute, #resource_attribute, #resource_class, #type

Instance Method Summary collapse

Methods inherited from Attribute

#block_value_for, #hash_attribute_dot_parts, #reference?, #references_many?, #references_one?, #resource_attribute_dot_parts

Constructor Details

#initialize(args = {}) ⇒ SerializerAttribute

Returns a new instance of SerializerAttribute.



8
9
10
11
12
13
# File 'lib/ledger_sync/serialization/serializer_attribute.rb', line 8

def initialize(args = {})
  super

  raise 'Missing hash_attribute' if hash_attribute.blank?
  raise 'block and resource_attribute cannot both be present' unless block.nil? || resource_attribute.nil?
end

Instance Method Details

#dot_value_for(resource:) ⇒ Object

Make nested/dot calls (e.g. vendor.ledger_id)



16
17
18
# File 'lib/ledger_sync/serialization/serializer_attribute.rb', line 16

def dot_value_for(resource:)
  resource_attribute_dot_parts.inject(resource) { |r, dot_method| r&.send(dot_method) }
end

#hash_attribute_hash_for(resource:) ⇒ Object



20
21
22
# File 'lib/ledger_sync/serialization/serializer_attribute.rb', line 20

def hash_attribute_hash_for(resource:)
  hash_attribute_hash_with(value: value(resource: resource))
end

#hash_attribute_hash_with(value:) ⇒ Object

Create nested hash for ledger

when hash_attribute = ‘Foo.Bar.Baz’, hash_attribute_hash_with(value: 123) Result: {

'Foo' => {
  'Bar' => {
    'Baz' => 123
  }
}

}



36
37
38
# File 'lib/ledger_sync/serialization/serializer_attribute.rb', line 36

def hash_attribute_hash_with(value:)
  hash_attribute_dot_parts.reverse.inject(value) { |a, n| { n => a } }
end

#value(resource:) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/ledger_sync/serialization/serializer_attribute.rb', line 40

def value(resource:)
  value = if block.nil?
            dot_value_for(resource: resource)
          else
            block_value_for(resource: resource)
          end

  type.convert(value: value)
end