diff options
author | Jerry Cheung <jollyjerry@gmail.com> | 2013-02-12 20:29:00 -0800 |
---|---|---|
committer | Jerry Cheung <jollyjerry@gmail.com> | 2013-02-12 20:29:00 -0800 |
commit | fc875ae8a3ee41b9d11683fbd560edabebfe1a2f (patch) | |
tree | 3427618a1559f00a8ab253cbf7d7ca9f0ec88c92 | |
parent | 58ebe3393263355cd714490d86192741d26a34d2 (diff) | |
parent | 62b3317a669400fdb8c2e07184749fc85abd7d36 (diff) | |
download | hashie-fc875ae8a3ee41b9d11683fbd560edabebfe1a2f.tar.gz |
Merge pull request #78 from intridea/merge-update-block
Allow a block for merge and update
-rw-r--r-- | lib/hashie/mash.rb | 12 | ||||
-rw-r--r-- | spec/hashie/mash_spec.rb | 6 |
2 files changed, 13 insertions, 5 deletions
diff --git a/lib/hashie/mash.rb b/lib/hashie/mash.rb index 3c4e6c7..5456bb3 100644 --- a/lib/hashie/mash.rb +++ b/lib/hashie/mash.rb @@ -141,20 +141,22 @@ module Hashie # Performs a deep_update on a duplicate of the # current mash. - def deep_merge(other_hash) - dup.deep_update(other_hash) + def deep_merge(other_hash, &blk) + dup.deep_update(other_hash, &blk) end alias_method :merge, :deep_merge # Recursively merges this mash with the passed # in hash, merging each hash in the hierarchy. - def deep_update(other_hash) + def deep_update(other_hash, &blk) other_hash.each_pair do |k,v| key = convert_key(k) if regular_reader(key).is_a?(Mash) and v.is_a?(::Hash) - regular_reader(key).deep_update(v) + regular_reader(key).deep_update(v, &blk) else - regular_writer(key, convert_value(v, true)) + value = convert_value(v, true) + value = blk.call(key, self[k], value) if blk + regular_writer(key, value) end end self diff --git a/spec/hashie/mash_spec.rb b/spec/hashie/mash_spec.rb index 95821f5..71f398d 100644 --- a/spec/hashie/mash_spec.rb +++ b/spec/hashie/mash_spec.rb @@ -159,6 +159,12 @@ describe Hashie::Mash do duped.details.email.should == "michael@intridea.com" duped.details.address.should == "Nowhere road" end + + # http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-update + it "accepts a block" do + duped = subject.merge(:details => {:address => "Pasadena CA"}) {|key, oldv, newv| [oldv, newv].join(', ')} + duped.details.address.should == 'Nowhere road, Pasadena CA' + end end describe "shallow update" do |