diff options
-rw-r--r-- | activesupport/lib/active_support/hash_with_indifferent_access.rb | 2 | ||||
-rw-r--r-- | activesupport/test/hash_with_indifferent_access_test.rb | 28 |
2 files changed, 29 insertions, 1 deletions
diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb index 42ae7e9b7b..5981763f0e 100644 --- a/activesupport/lib/active_support/hash_with_indifferent_access.rb +++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb @@ -69,7 +69,7 @@ module ActiveSupport super() update(constructor) - hash = constructor.to_hash + hash = constructor.is_a?(Hash) ? constructor : constructor.to_hash self.default = hash.default if hash.default self.default_proc = hash.default_proc if hash.default_proc else diff --git a/activesupport/test/hash_with_indifferent_access_test.rb b/activesupport/test/hash_with_indifferent_access_test.rb index 1d6a07ec5f..af96231801 100644 --- a/activesupport/test/hash_with_indifferent_access_test.rb +++ b/activesupport/test/hash_with_indifferent_access_test.rb @@ -836,4 +836,32 @@ class HashWithIndifferentAccessTest < ActiveSupport::TestCase assert_equal 3, hash_wia[:foo] assert_equal 3, hash_wia[:bar] end + + def test_should_copy_the_default_when_converting_non_hash_to_hash_with_indifferent_access + non_hash = Object.new + + def non_hash.to_hash + h = { foo: :bar } + h.default = :baz + h + end + + hash_wia = HashWithIndifferentAccess.new(non_hash) + assert_equal :bar, hash_wia[:foo] + assert_equal :baz, hash_wia[:missing] + end + + def test_should_copy_the_default_proc_when_converting_non_hash_to_hash_with_indifferent_access + non_hash = Object.new + + def non_hash.to_hash + h = { foo: :bar } + h.default_proc = ->(hash, key) { hash[key] = :baz } + h + end + + hash_wia = HashWithIndifferentAccess.new(non_hash) + assert_equal :bar, hash_wia[:foo] + assert_equal :baz, hash_wia[:missing] + end end |