Class: HashRemapper

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

Overview

Utility class to map original Hash keys to the new ones

Constant Summary collapse

VERSION =

Current Library Version

'0.4.2'

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 (source: :target)

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
41
# 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(Hash.new { |hash, key| hash[key] = Hash.new(&hash.default_proc) }) do |(from, to), acc|
    key, value = try_callable(from, to, data, acc) ||
                 try_digging(from, to, data, acc) ||
                 try_nesting(from, to, data, acc) ||
                 [to, data[from]]

    set_value(acc, key, value)
    acc
  end
end