Class: HashMapHash
- Inherits:
-
Object
- Object
- HashMapHash
- Defined in:
- lib/hash_map_hash.rb
Defined Under Namespace
Modules: DeepDup
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
10 11 12 |
# File 'lib/hash_map_hash.rb', line 10 def initialize(mapping) @mapping = mapping.extend(DeepDup) end |
Instance Attribute Details
#mapping ⇒ Object (readonly)
Returns the value of attribute mapping.
8 9 10 |
# File 'lib/hash_map_hash.rb', line 8 def mapping @mapping end |
Instance Method Details
#add_nested_properties(nested_properties) ⇒ Object
58 59 60 61 |
# File 'lib/hash_map_hash.rb', line 58 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
52 53 54 55 56 |
# File 'lib/hash_map_hash.rb', line 52 def map(source_data) mapping.deep_dup.each_with_object({}) do |(attribute_key, attribute_mapping), result| result[attribute_key] = filtered_deep_fetch source_data, Array(attribute_mapping) end end |