From a2e56c2d12e2b81ac1f5d6e83ef7b45739d2da20 Mon Sep 17 00:00:00 2001 From: Bruno Michel Date: Tue, 29 Jun 2010 22:31:32 +0200 Subject: [PATCH] Support for passing a block when merging HashWithIndifferentAccess --- .../active_support/hash_with_indifferent_access.rb | 6 ++-- activesupport/test/core_ext/hash_ext_test.rb | 22 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb index f64f0f4..29fe8e6 100644 --- a/activesupport/lib/active_support/hash_with_indifferent_access.rb +++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb @@ -50,7 +50,7 @@ module ActiveSupport # hash_1.update(hash_2) # => {"key"=>"New Value!"} # def update(other_hash) - other_hash.each_pair { |key, value| regular_writer(convert_key(key), convert_value(value)) } + other_hash.each_pair { |key, value| regular_writer(convert_key(key), block_given? ? yield(key, self[key], convert_value(value)) : convert_value(value)) } self end @@ -94,8 +94,8 @@ module ActiveSupport # Merges the instantized and the specified hashes together, giving precedence to the values from the second hash # Does not overwrite the existing hash. - def merge(hash) - self.dup.update(hash) + def merge(hash, &block) + self.dup.update(hash, &block) end # Performs the opposite of merge, with the keys and values from the first hash taking precedence over the second. diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index 7b2c109..ea42f74 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -213,6 +213,28 @@ class HashExtTest < Test::Unit::TestCase assert_equal 2, hash['b'] end + def test_indifferent_merging_with_block + hash = HashWithIndifferentAccess.new + hash[:a] = 'failure' + hash['b'] = 'failure' + hash['c'] = 'something' + + other = { 'a' => 'should not be a failure', :b => 'fail' } + + merged = hash.merge(other) { |k,o,n| n.size > o.size ? n : o } + + assert_equal HashWithIndifferentAccess, merged.class + assert_equal 'should not be a failure', merged[:a] + assert_equal 'failure', merged['b'] + assert_equal 'something', merged['c'] + + hash.update(other) { |k,o,n| n.size > o.size ? n : o } + + assert_equal 'should not be a failure', hash[:a] + assert_equal 'failure', hash['b'] + assert_equal 'something', hash['c'] + end + def test_indifferent_reverse_merging hash = HashWithIndifferentAccess.new('some' => 'value', 'other' => 'value') hash.reverse_merge!(:some => 'noclobber', :another => 'clobber') -- 1.7.0.4