diff options
author | Jim Myhrberg <contact@jimeh.me> | 2013-02-26 08:40:13 +0000 |
---|---|---|
committer | Jim Myhrberg <contact@jimeh.me> | 2013-02-26 08:40:13 +0000 |
commit | 4c453e5c3e02bee19f7e1c0a41a500368e8bb744 (patch) | |
tree | 068860cad0c833e7ee773055beb4644cd8049c98 | |
parent | 328cf56de6c39ffea06770207f21ea722b9497a0 (diff) | |
download | hashie-4c453e5c3e02bee19f7e1c0a41a500368e8bb744.tar.gz |
Add #replace to Hashie::Mash to achieve Hash-like behavior
-rw-r--r-- | lib/hashie/mash.rb | 5 | ||||
-rw-r--r-- | spec/hashie/mash_spec.rb | 23 |
2 files changed, 28 insertions, 0 deletions
diff --git a/lib/hashie/mash.rb b/lib/hashie/mash.rb index 4d25b3b..04d6980 100644 --- a/lib/hashie/mash.rb +++ b/lib/hashie/mash.rb @@ -175,6 +175,11 @@ module Hashie self end + def replace(other_hash) + (keys - other_hash.keys).each { |key| delete(key) } + other_hash.each { |key, value| self[key] = value } + end + # Will return true if the Mash has had a key # set in addition to normal respond_to? functionality. def respond_to?(method_name, include_private=false) diff --git a/spec/hashie/mash_spec.rb b/spec/hashie/mash_spec.rb index 6cd3994..78e0223 100644 --- a/spec/hashie/mash_spec.rb +++ b/spec/hashie/mash_spec.rb @@ -183,6 +183,29 @@ describe Hashie::Mash do end end + describe '#replace' do + before do + subject.replace(:middle_name => "Cain", + :details => {:city => "Imagination"}) + end + + it 'sets all specified keys to their corresponding values' do + subject.middle_name?.should be_true + subject.details?.should be_true + subject.middle_name.should == "Cain" + subject.details.city?.should be_true + subject.details.city.should == "Imagination" + end + + it 'leaves only specified keys' do + subject.keys.should == ['middle_name', 'details'] + subject.first_name?.should be_false + subject.first_name.should be_nil + subject.last_name?.should be_false + subject.last_name.should be_nil + end + end + describe 'delete' do it 'should delete with String key' do subject.delete('details') |