Module: Evil::Struct::Utils

Extended by:
Utils
Included in:
Utils
Defined in:
lib/evil/struct/utils.rb

Overview

Collection of utility methods to hashify and merge structures

Instance Method Summary collapse

Instance Method Details

#hashify(value) ⇒ Hash

Converts value to nested hash

Makes conversion through nested hashes, arrays, enumerables, and other objects that respond to to_a, to_h, to_hash, or each. Doesn’t convert nil (even though it responds to to_h and to_a).

Parameters:

  • value (Object)

Returns:

  • (Hash)


14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/evil/struct/utils.rb', line 14

def hashify(value)
  hash = to_h(value)
  list = to_a(value)

  if hash
    hash.each_with_object({}) { |(key, val), obj| obj[key] = hashify(val) }
  elsif list
    list.map { |item| hashify(item) }
  else
    value
  end
end

#merge(source, target) ⇒ Hash<Symbol, Object>

Shallowly merges target object to the source hash

The target object can be hash, or respond to either to_h, or to_hash. Before a merge, the keys of the target object are symbolized.

Parameters:

  • source (Hash<Symbol, Object>)
  • target (Hash, #to_h, #to_hash)

Returns:

  • (Hash<Symbol, Object>)


36
37
38
# File 'lib/evil/struct/utils.rb', line 36

def merge(source, target)
  source.merge(to_h(target))
end

#merge_deeply(source, target) ⇒ Object

Deeply merges target object to the source one

The nesting stops when a first non-hashified value reached. It do not merge arrays of hashes!

Parameters:

  • source (Object)
  • target (Object)

Returns:

  • (Object)


49
50
51
52
53
54
55
56
57
58
59
# File 'lib/evil/struct/utils.rb', line 49

def merge_deeply(source, target)
  source_hash = to_h(source)
  target_hash = to_h(target)
  return target unless source_hash && target_hash

  keys = (source_hash.keys | target_hash.keys)
  keys.each_with_object(source_hash) do |key, obj|
    next unless target_hash.key? key
    obj[key] = merge_deeply source_hash[key], target_hash[key]
  end
end