Class: HashRemapper

Inherits:
Object
  • Object
show all
Defined in:
lib/hash_remapper.rb

Overview

Utility class to map original Hash keys to the new ones

Constant Summary collapse

VERSION =

Current Library Version

'0.2.0'

Class Method Summary collapse

Class Method Details

.remap(data, pass_trough = false, mapping) ⇒ Hash

Remaps data Hash by renaming keys, creating new ones and optionally aggregating values

Examples:

HashRemapper.remap(
  {a: 1, b: 2, c: 3},
  true
  a: :one,
  b: :two
) # => { one: 1, two: 2, c: 3 }

Parameters:

  • data (Hash)

    the original Hash to remap

  • pass_trough (Boolean) (defaults to: false)

    the flag to pass the original key/value pairs (default: false)

  • mapping (Hash)

    the Hash which in the simplest case tells how to rename keys

Returns:

  • (Hash)

    remapped version of the original Hash (selected keys only or all the keys if we passed originals)



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/hash_remapper.rb', line 29

def remap(data, pass_trough = false, mapping)
  mapping = pass_trough_mapping(data, mapping) if pass_trough

  mapping.each_with_object({}) do |(from, to), acc|
    key, value = try_callable(from, to, data, acc) ||
                 try_digging(to, data) ||
                 [to, data[from]]

    acc[key] = value
    acc
  end
end