4 module Puppet::Parser::Functions
5 newfunction(:deep_merge, :type => :rvalue, :doc => <<-'DOC') do |args|
7 Recursively merges two or more hashes together and returns the resulting hash.
11 $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } }
12 $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } }
13 $merged_hash = deep_merge($hash1, $hash2)
15 The resulting hash is equivalent to:
17 $merged_hash = { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } }
19 When there is a duplicate key that is a hash, they are recursively merged.
20 When there is a duplicate key that is not a hash, the key in the rightmost hash will "win."
22 @return [Hash] The merged hash
26 raise Puppet::ParseError, "deep_merge(): wrong number of arguments (#{args.length}; must be at least 2)"
29 deep_merge = proc do |hash1, hash2|
30 hash1.merge(hash2) do |_key, old_value, new_value|
31 if old_value.is_a?(Hash) && new_value.is_a?(Hash)
32 deep_merge.call(old_value, new_value)
41 next if arg.is_a?(String) && arg.empty? # empty string is synonym for puppet's undef
42 # If the argument was not a hash, skip it.
43 unless arg.is_a?(Hash)
44 raise Puppet::ParseError, "deep_merge: unexpected argument type #{arg.class}, only expects hash arguments"
47 result = deep_merge.call(result, arg)