1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

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.
This commit is contained in:
Pranas Kiziela 2012-09-13 21:49:49 +03:00
parent 8692db59af
commit 54575d8797
3 changed files with 23 additions and 4 deletions

View file

@ -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 file

@ -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 file

@ -582,6 +582,16 @@ class HashExtTest < ActiveSupport::TestCase
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" } } })