module Hashie::Extensions::DeepMerge
@example Merge nested hashes
hash = { user: { name: 'Ada' } }.extend(Hashie::Extensions::DeepMerge) hash.deep_merge(user: { active: true }) # => { user: { name: 'Ada', active: true } }
Public Instance Methods
deep_merge(other_hash, &block)
click to toggle source
Returns a new hash with self and other_hash merged recursively.
@example Merge without changing the receiver
hash = { settings: { count: 1 } }.extend(Hashie::Extensions::DeepMerge) hash.deep_merge(settings: { count: 2 }) # => { settings: { count: 2 } } hash # => { settings: { count: 1 } }
# File lib/hashie/extensions/deep_merge.rb, line 15 def deep_merge(other_hash, &block) copy = _deep_dup(self) copy.extend(Hashie::Extensions::DeepMerge) unless copy.respond_to?(:deep_merge!) copy.deep_merge!(other_hash, &block) end
deep_merge!(other_hash, &block)
click to toggle source
Returns a new hash with self and other_hash merged recursively. Modifies the receiver in place.
@example Resolve a nested conflict with a block
hash = { settings: { count: 1 } }.extend(Hashie::Extensions::DeepMerge) hash.deep_merge!({ settings: { count: 2 } }) { |_key, old, new| old + new } hash # => { settings: { count: 3 } }
# File lib/hashie/extensions/deep_merge.rb, line 28 def deep_merge!(other_hash, &block) return self unless other_hash.is_a?(::Hash) _recursive_merge(self, other_hash, &block) self end
Private Instance Methods
_deep_dup(hash)
click to toggle source
# File lib/hashie/extensions/deep_merge.rb, line 37 def _deep_dup(hash) copy = hash.dup copy.each do |key, value| copy[key] = if value.is_a?(::Hash) _deep_dup(value) else Hashie::Utils.safe_dup(value) end end copy end
_recursive_merge(hash, other_hash) { |k, hash, v| ... }
click to toggle source
# File lib/hashie/extensions/deep_merge.rb, line 52 def _recursive_merge(hash, other_hash, &block) other_hash.each do |k, v| hash[k] = if hash.key?(k) && hash[k].is_a?(::Hash) && v.is_a?(::Hash) _recursive_merge(hash[k], v, &block) elsif v.is_a?(::Hash) _recursive_merge({}, v, &block) elsif hash.key?(k) && block_given? yield(k, hash[k], v) else v.respond_to?(:deep_dup) ? v.deep_dup : v end end hash end