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, #if_method, #resource_attribute, #resource_class, #type

Instance Method Summary collapse

Methods inherited from Attribute

#block_value_for, #hash_attribute_dot_parts, #reference?, #resource_attribute_dot_parts

Constructor Details

#initialize(args = {}) ⇒ SerializerAttribute

Returns a new instance of SerializerAttribute.



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/ledger_sync/serialization/serializer_attribute.rb', line 8

def initialize(args = {})
  super

  raise 'Missing hash_attribute' if hash_attribute.blank?

  if block.present?
    raise 'block and hash_attribute cannot both be present' if resource_attribute.present?
  else
    @resource_attribute ||= hash_attribute
  end
end

Instance Method Details

#dot_value_for(resource:) ⇒ Object

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



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

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



25
26
27
# File 'lib/ledger_sync/serialization/serializer_attribute.rb', line 25

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
  }
}

}



41
42
43
# File 'lib/ledger_sync/serialization/serializer_attribute.rb', line 41

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

#references_many?Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/ledger_sync/serialization/serializer_attribute.rb', line 45

def references_many?
  type.is_a?(Type::SerializerReferencesManyType)
end

#references_one?Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/ledger_sync/serialization/serializer_attribute.rb', line 49

def references_one?
  type.is_a?(Type::SerializerReferencesOneType)
end

#value(resource:) ⇒ Object



53
54
55
56
57
58
59
60
61
# File 'lib/ledger_sync/serialization/serializer_attribute.rb', line 53

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

  type.cast(value: value)
end