diff options
author | Jim Myhrberg <contact@jimeh.me> | 2013-02-26 08:40:44 +0000 |
---|---|---|
committer | Jim Myhrberg <contact@jimeh.me> | 2013-02-26 08:40:44 +0000 |
commit | 347bdb987f8a9d520c786a5356b1fd56d9703875 (patch) | |
tree | 4c9ac7429d431735f08d96758b57b2568dd74fa8 | |
parent | 4c453e5c3e02bee19f7e1c0a41a500368e8bb744 (diff) | |
download | hashie-347bdb987f8a9d520c786a5356b1fd56d9703875.tar.gz |
Add #replace to Hashie::Dash to achieve Hash-like behavior
-rw-r--r-- | lib/hashie/dash.rb | 6 | ||||
-rw-r--r-- | spec/hashie/dash_spec.rb | 14 |
2 files changed, 20 insertions, 0 deletions
diff --git a/lib/hashie/dash.rb b/lib/hashie/dash.rb index 8a1f6f7..ccee9aa 100644 --- a/lib/hashie/dash.rb +++ b/lib/hashie/dash.rb @@ -127,6 +127,12 @@ module Hashie super(property.to_s, value) end + def replace(other_hash) + other_hash = other_hash.merge(self.class.defaults) + (keys - other_hash.keys).each { |key| delete(key) } + other_hash.each { |key, value| self[key] = value } + end + private def initialize_attributes(attributes) diff --git a/spec/hashie/dash_spec.rb b/spec/hashie/dash_spec.rb index 1e1edc9..008f608 100644 --- a/spec/hashie/dash_spec.rb +++ b/spec/hashie/dash_spec.rb @@ -170,6 +170,20 @@ describe DashTest do described_class.defaults.should == { :count => 0 } end end + + describe '#replace' do + before { subject.replace(:first_name => "Cain") } + + it 'sets all specified keys to their corresponding values' do + subject.first_name.should == "Cain" + end + + it 'leaves only specified keys and keys with default values' do + subject.keys.should == ['first_name', 'count'] + subject.email.should be_nil + subject.count.should == 0 + end + end end describe Hashie::Dash, 'inheritance' do |