diff options
author | Peter Jaros <peter.a.jaros@gmail.com> | 2013-10-15 15:45:07 -0400 |
---|---|---|
committer | Peter Jaros <peter.a.jaros@gmail.com> | 2014-03-28 10:25:06 -0400 |
commit | 03f35a27dc88335550ca0ab1d21e46948c9f5093 (patch) | |
tree | c1ba24a651170c407b93f0d43696ba8622e551d6 /activesupport/test | |
parent | dd3ea17191e316aeebddaa7b176f6cfeee7a6365 (diff) | |
download | rails-03f35a27dc88335550ca0ab1d21e46948c9f5093.tar.gz rails-03f35a27dc88335550ca0ab1d21e46948c9f5093.tar.bz2 rails-03f35a27dc88335550ca0ab1d21e46948c9f5093.zip |
HashWithIndifferentAccess better respects #to_hash
In particular, `.new`, `#update`, `#merge`, `#replace` all accept
objects which respond to `#to_hash`, even if those objects are not
Hashes directly.
Diffstat (limited to 'activesupport/test')
-rw-r--r-- | activesupport/test/core_ext/hash_ext_test.rb | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index 40c8f03374..69a380c7cb 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -23,6 +23,16 @@ class HashExtTest < ActiveSupport::TestCase end end + class HashByConversion + def initialize(hash) + @hash = hash + end + + def to_hash + @hash + end + end + def setup @strings = { 'a' => 1, 'b' => 2 } @nested_strings = { 'a' => { 'b' => { 'c' => 3 } } } @@ -411,6 +421,12 @@ class HashExtTest < ActiveSupport::TestCase assert [updated_with_strings, updated_with_symbols, updated_with_mixed].all? { |h| h.keys.size == 2 } end + def test_update_with_to_hash_conversion + hash = HashWithIndifferentAccess.new + hash.update HashByConversion.new({ :a => 1 }) + assert_equal hash['a'], 1 + end + def test_indifferent_merging hash = HashWithIndifferentAccess.new hash[:a] = 'failure' @@ -430,6 +446,12 @@ class HashExtTest < ActiveSupport::TestCase assert_equal 2, hash['b'] end + def test_merge_with_to_hash_conversion + hash = HashWithIndifferentAccess.new + merged = hash.merge HashByConversion.new({ :a => 1 }) + assert_equal merged['a'], 1 + end + def test_indifferent_replace hash = HashWithIndifferentAccess.new hash[:a] = 42 @@ -442,6 +464,18 @@ class HashExtTest < ActiveSupport::TestCase assert_same hash, replaced end + def test_replace_with_to_hash_conversion + hash = HashWithIndifferentAccess.new + hash[:a] = 42 + + replaced = hash.replace(HashByConversion.new(b: 12)) + + assert hash.key?('b') + assert !hash.key?(:a) + assert_equal 12, hash[:b] + assert_same hash, replaced + end + def test_indifferent_merging_with_block hash = HashWithIndifferentAccess.new hash[:a] = 1 @@ -893,6 +927,12 @@ class HashExtTest < ActiveSupport::TestCase assert_equal({}, h.compact!) assert_equal({}, h) end + + def test_new_with_to_hash_conversion + hash = HashWithIndifferentAccess.new(HashByConversion.new(a: 1)) + assert hash.key?('a') + assert_equal 1, hash[:a] + end end class IWriteMyOwnXML |