summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSpencer Rogers <spencer1248@gmail.com>2013-11-30 12:03:05 -0700
committerSpencer Rogers <spencer1248@gmail.com>2013-11-30 12:03:05 -0700
commit5b132c6190c21b1328491d92a7cb7943de36c1b9 (patch)
tree3435cea54319af4343d195a833e3504ccd87efbb
parent05e3cba9241dc82df0c22f1cd508790c2500125c (diff)
downloadhashie-5b132c6190c21b1328491d92a7cb7943de36c1b9.tar.gz
Fix Dash#merge!
-rw-r--r--lib/hashie/dash.rb7
-rw-r--r--spec/hashie/dash_spec.rb29
2 files changed, 36 insertions, 0 deletions
diff --git a/lib/hashie/dash.rb b/lib/hashie/dash.rb
index 42056e7..8d64442 100644
--- a/lib/hashie/dash.rb
+++ b/lib/hashie/dash.rb
@@ -135,6 +135,13 @@ module Hashie
new_dash
end
+ def merge!(other_hash)
+ other_hash.each do |k,v|
+ self[k] = block_given? ? yield(k, self[k], v) : v
+ end
+ self
+ end
+
def replace(other_hash)
other_hash = self.class.defaults.merge(other_hash)
(keys - other_hash.keys).each { |key| delete(key) }
diff --git a/spec/hashie/dash_spec.rb b/spec/hashie/dash_spec.rb
index b6467c3..22704ae 100644
--- a/spec/hashie/dash_spec.rb
+++ b/spec/hashie/dash_spec.rb
@@ -176,6 +176,35 @@ describe DashTest do
end
end
+ describe '#merge!' do
+ it 'modifies the existing instance of the Dash' do
+ original_dash = subject.merge!(:first_name => 'Robert')
+ subject.object_id.should == original_dash.object_id
+ end
+
+ it 'merges the given hash' do
+ subject.merge!(:first_name => 'Robert', :email => 'robert@example.com')
+ subject.first_name.should == 'Robert'
+ subject.email.should == 'robert@example.com'
+ end
+
+ it 'fails with non-existent properties' do
+ expect { subject.merge!(:middle_name => 'James') }.to raise_error(NoMethodError)
+ end
+
+ it 'errors out when attempting to set a required property to nil' do
+ expect { subject.merge!(:first_name => nil) }.to raise_error(ArgumentError)
+ end
+
+ context "given a block" do
+ it "sets merged key's values to the block's return value" do
+ subject.merge!(:first_name => 'Jim') do |key, oldval, newval|
+ "#{key}: #{newval} #{oldval}"
+ end.first_name.should == 'first_name: Jim Bob'
+ end
+ end
+ end
+
describe 'properties' do
it 'lists defined properties' do
described_class.properties.should == Set.new([:first_name, :email, :count])