From ca92d44e7637ae6d28d6b88b67873d2795290cb5 Mon Sep 17 00:00:00 2001 From: Andrew Moreland Date: Sun, 9 Aug 2009 15:38:30 -0700 Subject: Support deep-merging HashWithIndifferentAccess. [#2732 state:committed] Signed-off-by: Jeremy Kemper --- activesupport/lib/active_support/core_ext/hash/deep_merge.rb | 9 +++++---- activesupport/test/core_ext/hash_ext_test.rb | 12 ++++++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/hash/deep_merge.rb b/activesupport/lib/active_support/core_ext/hash/deep_merge.rb index ffde34a741..24d0a2a481 100644 --- a/activesupport/lib/active_support/core_ext/hash/deep_merge.rb +++ b/activesupport/lib/active_support/core_ext/hash/deep_merge.rb @@ -1,11 +1,12 @@ class Hash # Returns a new hash with +self+ and +other_hash+ merged recursively. def deep_merge(other_hash) - merge(other_hash) do |key, oldval, newval| - oldval = oldval.to_hash if oldval.respond_to?(:to_hash) - newval = newval.to_hash if newval.respond_to?(:to_hash) - oldval.is_a?( Hash ) && newval.is_a?( Hash ) ? oldval.deep_merge(newval) : newval + target = dup + other_hash.each_pair do |k,v| + tv = target[k] + target[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_merge(v) : v end + target end # Returns a new hash with +self+ and +other_hash+ merged recursively. diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index 8b0f3fc33c..eb4c37aaf0 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -265,6 +265,18 @@ class HashExtTest < Test::Unit::TestCase 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" } } }) + hash_3 = { :a => 1, :c => { :c1 => 2, :c3 => { :d2 => "d2" } } } + expected = { "a" => 1, "b" => "b", "c" => { "c1" => 2, "c2" => "c2", "c3" => { "d1" => "d1", "d2" => "d2" } } } + assert_equal expected, hash_1.deep_merge(hash_2) + assert_equal expected, hash_1.deep_merge(hash_3) + + hash_1.deep_merge!(hash_2) + assert_equal expected, hash_1 + end + def test_reverse_merge defaults = { :a => "x", :b => "y", :c => 10 }.freeze options = { :a => 1, :b => 2 } -- cgit v1.2.3