summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--lib/hashie/extensions/indifferent_access.rb10
-rw-r--r--spec/hashie/extensions/indifferent_access_spec.rb25
2 files changed, 33 insertions, 2 deletions
diff --git a/lib/hashie/extensions/indifferent_access.rb b/lib/hashie/extensions/indifferent_access.rb
index 56af066..13218a9 100644
--- a/lib/hashie/extensions/indifferent_access.rb
+++ b/lib/hashie/extensions/indifferent_access.rb
@@ -27,7 +27,7 @@ module Hashie
base.class_eval do
alias_method :regular_writer, :[]=
alias_method :[]=, :indifferent_writer
- %w(default update fetch delete key? values_at).each do |m|
+ %w(default update replace fetch delete key? values_at).each do |m|
alias_method "regular_#{m}", m
alias_method m, "indifferent_#{m}"
end
@@ -95,7 +95,13 @@ module Hashie
def indifferent_values_at(*indices); indices.map{|i| self[i] } end
def indifferent_access?; true end
-
+
+ def indifferent_replace(other_hash)
+ (keys - other_hash.keys).each { |key| delete(key) }
+ other_hash.each { |key, value| self[key] = value }
+ self
+ end
+
protected
def hash_lacking_indifference?(other)
diff --git a/spec/hashie/extensions/indifferent_access_spec.rb b/spec/hashie/extensions/indifferent_access_spec.rb
index 382d930..d0522fc 100644
--- a/spec/hashie/extensions/indifferent_access_spec.rb
+++ b/spec/hashie/extensions/indifferent_access_spec.rb
@@ -71,4 +71,29 @@ describe Hashie::Extensions::IndifferentAccess do
Hash.new.should_not be_respond_to(:indifferent_access?)
end
end
+
+ describe '#replace' do
+ subject do
+ IndifferentHash.new(:foo => 'bar').replace(:bar => 'baz', :hi => 'bye')
+ end
+
+ it 'returns self' do
+ subject.should be_a(IndifferentHash)
+ end
+
+ it 'should remove old keys' do
+ [:foo, 'foo'].each do |k|
+ subject[k].should be_nil
+ subject.key?(k).should be_false
+ end
+ end
+
+ it 'creates new keys with indifferent access' do
+ [:bar, 'bar', :hi, 'hi'].each { |k| subject.key?(k).should be_true }
+ subject[:bar].should == 'baz'
+ subject['bar'].should == 'baz'
+ subject[:hi].should == 'bye'
+ subject['hi'].should == 'bye'
+ end
+ end
end