Skip to content

Commit

Permalink
Fix Dash#merge!
Browse files Browse the repository at this point in the history
  • Loading branch information
sarogers committed Nov 30, 2013
1 parent 05e3cba commit 5b132c6
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/hashie/dash.rb
Expand Up @@ -135,6 +135,13 @@ def merge(other_hash)
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) }
Expand Down
29 changes: 29 additions & 0 deletions spec/hashie/dash_spec.rb
Expand Up @@ -176,6 +176,35 @@ class DeferredTest < Hashie::Dash
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])
Expand Down

0 comments on commit 5b132c6

Please sign in to comment.