Skip to content

Commit

Permalink
Merge pull request #25 from nilo85/master
Browse files Browse the repository at this point in the history
Added:keep_array_duplicates option + test
  • Loading branch information
Fryguy committed Aug 2, 2016
2 parents a7dbf33 + cb04ffd commit f9674d2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
14 changes: 13 additions & 1 deletion lib/deep_merge/core.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ class InvalidParameter < StandardError; end
# Set to string value to run "Array::join" then "String::split" against all arrays
# :merge_hash_arrays DEFAULT: false
# Set to true to merge hashes within arrays
# :keep_array_duplicates DEFAULT: false
# Set to true to preserve duplicate array entries
# :merge_debug DEFAULT: false
# Set to true to get console output of merge process for debugging
#
Expand Down Expand Up @@ -64,7 +66,13 @@ class InvalidParameter < StandardError; end
# dest = {:x => [{:z => 2}]}
# dest.deep_merge!(source, {:merge_hash_arrays => true})
# Results: {:x => [{:y => 1, :z => 2}]}
#
#
# :keep_array_duplicates => merges arrays within hashes but keeps duplicate elements
# source = {:x => {:y => [1,2,2,2,3]}}
# dest = {:x => {:y => [4,5,6]}}
# dest.deep_merge!(source, {:keep_array_duplicates => true})
# Results: {:x => {:y => [1,2,2,2,3,4,5,6]}}
#
# There are many tests for this library - and you can learn more about the features
# and usages of deep_merge! by just browsing the test examples
def self.deep_merge!(source, dest, options = {})
Expand All @@ -84,6 +92,8 @@ def self.deep_merge!(source, dest, options = {})
merge_hash_arrays = options[:merge_hash_arrays] || false
# request to extend existing arrays, instead of overwriting them
extend_existing_arrays = options[:extend_existing_arrays] || false
# request that arrays keep duplicate elements
keep_array_duplicates = options[:keep_array_duplicates] || false

di = options[:debug_indent] || ''
# do nothing if source is nil
Expand Down Expand Up @@ -168,6 +178,8 @@ def self.deep_merge!(source, dest, options = {})
end
list += source[dest.count..-1] if source.count > dest.count
dest = list
elsif keep_array_duplicates
dest = dest.concat(source)
else
dest = dest | source
end
Expand Down
10 changes: 10 additions & 0 deletions test/test_deep_merge.rb
Original file line number Diff line number Diff line change
Expand Up @@ -622,5 +622,15 @@ def test_deep_merge
hash_src = {"item" => s2 }
DeepMerge::deep_merge!(hash_src, hash_dst)
assert_equal({"item" => ""}, hash_dst)

######################################
# tests for "keep_array_duplicates" option
hash_src = {"item" => ["2", "3"]}
hash_dst = {"item" => ["1", "2"]}
DeepMerge::deep_merge!(hash_src, hash_dst, {:keep_array_duplicates => true})
assert_equal({"item" => ["1", "2", "2", "3"]}, hash_dst)



end # test_deep_merge
end

0 comments on commit f9674d2

Please sign in to comment.