Class: Jac::Configuration::Merger

Inherits:
Object
  • Object
show all
Defined in:
lib/jac/merger.rb

Overview

Merges two hashes with following value resolve strategy:

  • When having both ‘that: Hash` and `other: Hash` for same key will merge them with same strategy and return result

  • When having Set and Enumerable will join two sets into one

  • When having Set and nil will return Set

  • Return ‘other` value in all other cases

Instance Method Summary collapse

Instance Method Details

#merge(base, other) ⇒ Hash

Returns a new hash with base and overrides merged recursively.

Parameters:

  • base (Hash)

    values

  • other (Hash)

    values

Returns:

  • (Hash)

    updated hash



17
18
19
# File 'lib/jac/merger.rb', line 17

def merge(base, other)
  merge!(base.dup, other)
end

#merge!(base, other) ⇒ Hash

Returns a new hash with base and overrides merged recursively. Updates receiver

Parameters:

  • base (Hash)

    values

  • other (Hash)

    values

Returns:

  • (Hash)

    updated base hash



26
27
28
# File 'lib/jac/merger.rb', line 26

def merge!(base, other)
  base.merge!(other, &method(:resolve_values))
end

#resolve_values(_key, base, other) ⇒ Object

Returns resolved value.

Parameters:

  • _key (Object)
  • base (Object)
  • other (Object)

Returns:

  • (Object)

    resolved value



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/jac/merger.rb', line 34

def resolve_values(_key, base, other)
  if base.nil? && other.nil?
    nil
  elsif to_hash?(base, other)
    merge(base, other)
  elsif to_set?(base, other)
    Set.new(base) + Set.new(other)
  else
    other
  end
end