Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Skip merging if the destination is nil #20

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions lib/deep_merge/core.rb
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,13 @@ def self.deep_merge!(source, dest, options = {})
source.each do |src_key, src_value|
if dest.kind_of?(Hash)
puts "#{di} looping: #{src_key.inspect} => #{src_value.inspect} :: #{dest.inspect}" if merge_debug
if dest[src_key]
puts "#{di} ==>merging: #{src_key.inspect} => #{src_value.inspect} :: #{dest[src_key].inspect}" if merge_debug
dest[src_key] = deep_merge!(src_value, dest[src_key], options.merge(:debug_indent => di + ' '))
if dest.has_key?(src_key)
if dest[src_key].nil?
puts "#{di} ==>skipping: #{src_key.inspect} => #{src_value.inspect} :: #{dest[src_key].inspect}" if merge_debug
else
puts "#{di} ==>merging: #{src_key.inspect} => #{src_value.inspect} :: #{dest[src_key].inspect}" if merge_debug
dest[src_key] = deep_merge!(src_value, dest[src_key], options.merge(:debug_indent => di + ' '))
end
else # dest[src_key] doesn't exist so we want to create and overwrite it (but we do this via deep_merge!)
puts "#{di} ==>merging over: #{src_key.inspect} => #{src_value.inspect}" if merge_debug
# note: we rescue here b/c some classes respond to "dup" but don't implement it (Numeric, TrueClass, FalseClass, NilClass among maybe others)
Expand Down
15 changes: 15 additions & 0 deletions test/test_deep_merge.rb
Original file line number Diff line number Diff line change
Expand Up @@ -604,5 +604,20 @@ def test_deep_merge
hash_src = {"item" => s2 }
DeepMerge::deep_merge!(hash_src, hash_dst)
assert_equal({"item" => ""}, hash_dst)

################################
# Test ignoring nil destination

# if the destination is nil, skip merging it
hash_src = {"foo" => {"bar" => 1} }
hash_dst = {"foo" => {"bar" => nil} }
DeepMerge::deep_merge!(hash_src, hash_dst)
assert_equal({"foo" => {"bar" => nil}}, hash_dst)

# if the destination does not exists, merge it
hash_src = {"foo" => {"bar" => 1} }
hash_dst = {"foo" => {} }
DeepMerge::deep_merge!(hash_src, hash_dst)
assert_equal({"foo" => {"bar" => 1}}, hash_dst)
end # test_deep_merge
end