Skip to content
Browse files

Allow passing block to deep_merge and deep_merge!

Hash#merge accepts block that you can use to customize how hash values
are merged. This change makes merge and deep_merge compatible.
  • Loading branch information...
1 parent 8692db5 commit 54575d87973b95cbd278fbe086b70761584d286d @pranas pranas committed Sep 13, 2012
View
3 activesupport/CHANGELOG.md
@@ -1,5 +1,8 @@
## Rails 4.0.0 (unreleased) ##
+* An optional block can be passed to `Hash#deep_merge`. The block will be invoked for each duplicated key
+ and used to resolve the conflict. *Pranas Kiziela*
+
* ActiveSupport::Deprecation is now a class. It is possible to create an instance
of deprecator. Backwards compatibility has been preserved.
View
14 activesupport/lib/active_support/core_ext/hash/deep_merge.rb
@@ -6,15 +6,21 @@ class Hash
#
# h1.deep_merge(h2) #=> {:x => {:y => [7, 8, 9]}, :z => "xyz"}
# h2.deep_merge(h1) #=> {:x => {:y => [4, 5, 6]}, :z => [7, 8, 9]}
- def deep_merge(other_hash)
- dup.deep_merge!(other_hash)
+ # h1.deep_merge(h2) { |key, old, new| Array.wrap(old) + Array.wrap(new) }
+ # #=> {:x => {:y => [4, 5, 6, 7, 8, 9]}, :z => [7, 8, 9, "xyz"]}
+ def deep_merge(other_hash, &block)
+ dup.deep_merge!(other_hash, &block)
end
# Same as +deep_merge+, but modifies +self+.
- def deep_merge!(other_hash)
+ def deep_merge!(other_hash, &block)
other_hash.each_pair do |k,v|
tv = self[k]
- self[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_merge(v) : v
+ if tv.is_a?(Hash) && v.is_a?(Hash)
+ self[k] = tv.deep_merge(v, &block)
+ else
+ self[k] = block && tv ? block.call(k, tv, v) : v
+ end
end
self
end
View
10 activesupport/test/core_ext/hash_ext_test.rb
@@ -582,6 +582,16 @@ def test_deep_merge
assert_equal expected, hash_1
end
+ def test_deep_merge_with_block
+ hash_1 = { :a => "a", :b => "b", :c => { :c1 => "c1", :c2 => "c2", :c3 => { :d1 => "d1" } } }
+ hash_2 = { :a => 1, :c => { :c1 => 2, :c3 => { :d2 => "d2" } } }
+ expected = { :a => [:a, "a", 1], :b => "b", :c => { :c1 => [:c1, "c1", 2], :c2 => "c2", :c3 => { :d1 => "d1", :d2 => "d2" } } }
+ assert_equal(expected, hash_1.deep_merge(hash_2) { |k,o,n| [k, o, n] })
+
+ hash_1.deep_merge!(hash_2) { |k,o,n| [k, o, n] }
+ assert_equal expected, hash_1
+ end
+
def test_deep_merge_on_indifferent_access
hash_1 = HashWithIndifferentAccess.new({ :a => "a", :b => "b", :c => { :c1 => "c1", :c2 => "c2", :c3 => { :d1 => "d1" } } })
hash_2 = HashWithIndifferentAccess.new({ :a => 1, :c => { :c1 => 2, :c3 => { :d2 => "d2" } } })

0 comments on commit 54575d8

Please sign in to comment.
Something went wrong with that request. Please try again.