Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/mapped-record/hash/mappable.rb

Instance Method Summary collapse

Instance Method Details

#map_with(named_mapping) ⇒ Object

Returns a new Hash where the keys have been swapped with those defined in Mapping[named_mapping].



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/mapped-record/hash/mappable.rb', line 3

def map_with(named_mapping)
  if Mapping.has?(named_mapping)
    m = Mapping[named_mapping]

    result = self.inject({}) do |result, element|
      mapping = m[element.first]

      to = mapping[:to] if mapping
      proc = mapping[:filter] if mapping

      if to
        result[to] = element.last unless proc
        result[to] = proc.call(element.last) if proc
      end

      result
    end
  end
end