Module: Collapsium::RecursiveMerge

Extended by:
ViralCapabilities
Included in:
UberHash
Defined in:
lib/collapsium/recursive_merge.rb

Overview

Provides recursive merge functions for hashes.

Constant Summary

Constants included from ViralCapabilities

ViralCapabilities::DEFAULT_ANCESTORS, ViralCapabilities::READ_METHODS, ViralCapabilities::WRITE_METHODS

Constants included from Support::Methods

Support::Methods::WRAPPER_HASH

Instance Method Summary collapse

Methods included from ViralCapabilities

call_virality, copy_mods, enhance, enhance_array_value, enhance_hash_value, enhance_value, extended, extended, included, included, prepended, prepended, set_ancestors

Methods included from Support::Methods

loop_detected?, repeated, #resolve_helpers, #wrap_method, wrappers

Instance Method Details

#recursive_merge(other, overwrite = true) ⇒ Object

Same as ‘dup.recursive_merge!`

Parameters:

  • other (Hash)

    the hash to merge into ‘:self`

  • overwrite (Boolean) (defaults to: true)

    see method description.



57
58
59
# File 'lib/collapsium/recursive_merge.rb', line 57

def recursive_merge(other, overwrite = true)
  return dup.recursive_merge!(other, overwrite)
end

#recursive_merge!(other, overwrite = true) ⇒ Object

Recursively merge ‘:other` into this Hash.

This starts by merging the leaf-most Hash entries. Arrays are merged by addition.

For everything that’s neither Hash or Array, if the ‘:overwrite` parameter is true, the entry from `:other` is used. Otherwise the entry from `:self` is used.

Parameters:

  • other (Hash)

    the hash to merge into ‘:self`

  • overwrite (Boolean) (defaults to: true)

    see method description.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/collapsium/recursive_merge.rb', line 32

def recursive_merge!(other, overwrite = true)
  if other.nil?
    return self
  end

  merger = proc do |_, v1, v2|
    # rubocop:disable Style/GuardClause
    if v1.is_a? Hash and v2.is_a? Hash
      next v1.merge!(v2, &merger)
    elsif v1.is_a? Array and v2.is_a? Array
      next v1 + v2
    end
    if overwrite
      next v2
    else
      next v1
    end
    # rubocop:enable Style/GuardClause
  end
  merge!(other, &merger)
end