Module: Collapsium::RecursiveMerge

Included in:
UberHash
Defined in:
lib/collapsium/recursive_merge.rb

Overview

Provides recursive merge functions for hashes.

Instance Method Summary collapse

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.



51
52
53
54
55
# File 'lib/collapsium/recursive_merge.rb', line 51

def recursive_merge(other, overwrite = true)
  copy = dup
  copy.extend(RecursiveMerge)
  return copy.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.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/collapsium/recursive_merge.rb', line 26

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