Method: Dry::Transformer::HashTransformations.deep_merge

Defined in:
lib/dry/transformer/hash_transformations.rb

.deep_merge(hash, other) ⇒ Hash

Merge a hash recursively

Examples:


input = { 'foo' => 'bar', 'baz' => { 'one' => 1 } }
other = { 'foo' => 'buz', 'baz' => { :one => 'one', :two => 2 } }

t(:deep_merge)[input, other]
# => { 'foo' => "buz", :baz => { :one => 'one', 'one' => 1, :two => 2 } }

Parameters:

  • (Hash)
  • (Hash)

Returns:

  • (Hash)


435
436
437
438
439
440
441
442
443
444
# File 'lib/dry/transformer/hash_transformations.rb', line 435

def self.deep_merge(hash, other)
  Hash[hash].merge(other) do |_, original_value, new_value|
    if original_value.respond_to?(:to_hash) &&
       new_value.respond_to?(:to_hash)
      deep_merge(Hash[original_value], Hash[new_value])
    else
      new_value
    end
  end
end