Class: HashMapHash
- Inherits:
-
Object
- Object
- HashMapHash
- Defined in:
- lib/hash_map_hash.rb
Instance Attribute Summary collapse
-
#mapping ⇒ Object
readonly
Returns the value of attribute mapping.
Instance Method Summary collapse
- #add_nested_properties(nested_properties) ⇒ Object
-
#initialize(mapping) ⇒ HashMapHash
constructor
A new instance of HashMapHash.
-
#map(source_data) ⇒ Object
Data sample (source_data).
Constructor Details
#initialize(mapping) ⇒ HashMapHash
Returns a new instance of HashMapHash.
4 5 6 |
# File 'lib/hash_map_hash.rb', line 4 def initialize(mapping) @mapping = mapping end |
Instance Attribute Details
#mapping ⇒ Object (readonly)
Returns the value of attribute mapping.
2 3 4 |
# File 'lib/hash_map_hash.rb', line 2 def mapping @mapping end |
Instance Method Details
#add_nested_properties(nested_properties) ⇒ Object
52 53 54 55 |
# File 'lib/hash_map_hash.rb', line 52 def add_nested_properties(nested_properties) @mapping.merge! nested_mapping(nested_properties) if nested_properties.any? self end |
#map(source_data) ⇒ Object
Data sample (source_data)
{ ‘Contractors’ =>
{ 'Contractor' =>
[
{
'Value' => 'FirstAid, Moscow',
'Role' => 'Payer'
},
{
'Value' => '84266',
'OfficialName' => 'FirstAid, Moscow (442, Glow st)',
'Role' => 'Receiver'
}
]
},
'Items' => {
'NumberOfPositions' => 10
},
'Total' => 123.45
}
To get data, we should pass a mapping:
mapping =
payer: ['Contractors', 'Contractor', %w(Role Payer), 'Value'],
receiver: ['Contractors', 'Contractor', %w(Role Receiver), 'Value'],
amount: ['Items', 'NumberOfPositions'],
summ: 'Total'
output:
payer: 'FirstAid, Moscow',
receiver: '84266',
amount: 10,
summ: 123.45
46 47 48 49 50 |
# File 'lib/hash_map_hash.rb', line 46 def map(source_data) mapping.dup.each_with_object({}) do |(attribute_key, attribute_mapping), result| result[attribute_key] = filtered_deep_fetch source_data, Array(attribute_mapping) end end |