Module: Esse::HashUtils

Defined in:
lib/esse/primitives/hash_utils.rb

Overview

The idea here is to add useful methods to the ruby standard objects without monkey patching them

Class Method Summary collapse

Class Method Details

.deep_dup(hash) ⇒ Object



9
10
11
12
13
14
15
16
17
18
# File 'lib/esse/primitives/hash_utils.rb', line 9

def deep_dup(hash)
  hash.each_with_object({}) do |(key, value), result|
    result[key] = \
      if value.is_a?(Hash)
        deep_dup(value)
      else
        value
      end
  end
end

.deep_merge(target, source) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/esse/primitives/hash_utils.rb', line 31

def deep_merge(target, source)
  target.merge(source) do |key, oldval, newval|
    if oldval.is_a?(Hash) && newval.is_a?(Hash)
      deep_merge(oldval, newval)
    else
      newval
    end
  end
end

.deep_merge!(target, source) ⇒ Object



41
42
43
44
45
46
47
48
49
# File 'lib/esse/primitives/hash_utils.rb', line 41

def deep_merge!(target, source)
  target.merge!(source) do |key, oldval, newval|
    if oldval.is_a?(Hash) && newval.is_a?(Hash)
      deep_merge!(oldval, newval)
    else
      newval
    end
  end
end

.deep_transform_keys(hash, &block) ⇒ Object



20
21
22
23
24
25
26
27
28
29
# File 'lib/esse/primitives/hash_utils.rb', line 20

def deep_transform_keys(hash, &block)
  hash.each_with_object({}) do |(key, value), result|
    result[yield(key)] = \
      if value.is_a?(Hash)
        deep_transform_keys(value, &block)
      else
        value
      end
  end
end

.explode_keys(hash, separator = '.') ⇒ Object



51
52
53
54
55
56
57
58
59
# File 'lib/esse/primitives/hash_utils.rb', line 51

def explode_keys(hash, separator = '.')
  hash.each_with_object({}) do |(key, value), result|
    is_symbol = key.is_a?(Symbol)
    keys = key.to_s.split(separator)
    last_key = keys.pop
    current = keys.reduce(result) { |memo, k| memo[is_symbol ? k.to_sym : k] ||= {} }
    current[is_symbol ? last_key.to_sym : last_key] = value
  end
end