aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--activesupport/CHANGELOG2
-rw-r--r--activesupport/lib/active_support/core_ext/hash/indifferent_access.rb11
-rw-r--r--activesupport/test/core_ext/hash_ext_test.rb22
3 files changed, 31 insertions, 4 deletions
diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG
index 94470cf139..6d81723705 100644
--- a/activesupport/CHANGELOG
+++ b/activesupport/CHANGELOG
@@ -1,5 +1,7 @@
*SVN*
+* Fixed HashWithIndifferentAccess#default #5586 [chris@seagul.co.uk]
+
* More compatible Hash.create_from_xml. #5523 [nunemaker@gmail.com]
* Added Enumerable#sum for calculating a sum from the elements [DHH, jonathan@daikini.com]. Examples:
diff --git a/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb b/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb
index 1f645fabc9..9af626c8da 100644
--- a/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb
+++ b/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb
@@ -11,9 +11,10 @@ class HashWithIndifferentAccess < Hash
end
end
- def default(key)
- self[key.to_s] if key.is_a?(Symbol)
- end
+ def default(key = nil)
+ value = self[key.to_s] if key.is_a?(Symbol)
+ value ? value : super
+ end
alias_method :regular_writer, :[]= unless method_defined?(:regular_writer)
alias_method :regular_update, :update unless method_defined?(:regular_update)
@@ -74,7 +75,9 @@ module ActiveSupport #:nodoc:
module Hash #:nodoc:
module IndifferentAccess #:nodoc:
def with_indifferent_access
- HashWithIndifferentAccess.new(self)
+ hash = HashWithIndifferentAccess.new(self)
+ hash.default = self.default
+ hash
end
end
end
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb
index bd197a7e4e..327d884ecd 100644
--- a/activesupport/test/core_ext/hash_ext_test.rb
+++ b/activesupport/test/core_ext/hash_ext_test.rb
@@ -380,4 +380,26 @@ class HashToXmlTest < Test::Unit::TestCase
assert_equal expected_topic_hash, Hash.create_from_xml(topic_xml)["rsp"]["photos"]["photo"]
end
+
+ def test_should_use_default_value_for_unknown_key
+ hash_wia = HashWithIndifferentAccess.new(3)
+ assert_equal 3, hash_wia[:new_key]
+ end
+
+ def test_should_use_default_value_if_no_key_is_supplied
+ hash_wia = HashWithIndifferentAccess.new(3)
+ assert_equal 3, hash_wia.default
+ end
+
+ def test_should_nil_if_no_default_value_is_supplied
+ hash_wia = HashWithIndifferentAccess.new
+ assert_nil hash_wia.default
+ end
+
+ def test_should_copy_the_default_value_when_converting_to_hash_with_indifferent_access
+ hash = Hash.new(3)
+ hash_wia = hash.with_indifferent_access
+ assert_equal 3, hash_wia.default
+ end
+
end \ No newline at end of file