Skip to content

Commit

Permalink
Ensure that HashWithIndifferentAccess duplication preserves class (fo…
Browse files Browse the repository at this point in the history
…r sublclasses) and default value [#5724 state:resolved]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
  • Loading branch information
laserlemon authored and spastorino committed Nov 7, 2010
1 parent 6709078 commit 02039e9
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
Expand Up @@ -28,7 +28,7 @@ def default(key = nil)
end

def self.new_from_hash_copying_default(hash)
ActiveSupport::HashWithIndifferentAccess.new(hash).tap do |new_hash|
new(hash).tap do |new_hash|
new_hash.default = hash.default
end
end
Expand Down Expand Up @@ -97,7 +97,9 @@ def values_at(*indices)

# Returns an exact copy of the hash.
def dup
HashWithIndifferentAccess.new(self)
self.class.new(self).tap do |new_hash|
new_hash.default = default
end
end

# Merges the instantized and the specified hashes together, giving precedence to the values from the second hash
Expand Down
15 changes: 14 additions & 1 deletion activesupport/test/core_ext/hash_ext_test.rb
Expand Up @@ -6,6 +6,9 @@
require 'active_support/core_ext/object/conversions'

class HashExtTest < Test::Unit::TestCase
class IndifferentHash < HashWithIndifferentAccess
end

def setup
@strings = { 'a' => 1, 'b' => 2 }
@symbols = { :a => 1, :b => 2 }
Expand Down Expand Up @@ -267,7 +270,6 @@ def test_to_options_on_indifferent_preserves_hash
assert_equal 1, h['first']
end


def test_indifferent_subhashes
h = {'user' => {'id' => 5}}.with_indifferent_access
['user', :user].each {|user| [:id, 'id'].each {|id| assert_equal 5, h[user][id], "h[#{user.inspect}][#{id.inspect}] should be 5"}}
Expand All @@ -276,6 +278,17 @@ def test_indifferent_subhashes
['user', :user].each {|user| [:id, 'id'].each {|id| assert_equal 5, h[user][id], "h[#{user.inspect}][#{id.inspect}] should be 5"}}
end

def test_indifferent_duplication
# Should preserve default value
h = HashWithIndifferentAccess.new
h.default = '1234'
assert_equal h.default, h.dup.default

# Should preserve class for subclasses
h = IndifferentHash.new
assert_equal h.class, h.dup.class
end

def test_assert_valid_keys
assert_nothing_raised do
{ :failure => "stuff", :funny => "business" }.assert_valid_keys([ :failure, :funny ])
Expand Down

0 comments on commit 02039e9

Please sign in to comment.