1 # This class has dubious semantics and we only have it so that
2 # people can write params[:key] instead of params['key']
3 # and they get the same value for both keys.
5 class HashWithIndifferentAccess
< Hash
6 def initialize(constructor
= {})
7 if constructor
.is_a
?(Hash
)
15 def default(key
= nil)
16 if key
.is_a
?(Symbol
) && include?(key
= key
.to_s
)
23 alias_method
:regular_writer, :[]= unless method_defined
?(:regular_writer)
24 alias_method
:regular_update, :update unless method_defined
?(:regular_update)
26 # Assigns a new value to the hash:
28 # hash = HashWithIndifferentAccess.new
29 # hash[:key] = "value"
32 regular_writer(convert_key(key
), convert_value(value
))
35 # Updates the instantized hash with values from the second:
37 # hash_1 = HashWithIndifferentAccess.new
38 # hash_1[:key] = "value"
40 # hash_2 = HashWithIndifferentAccess.new
41 # hash_2[:key] = "New Value!"
43 # hash_1.update(hash_2) # => {"key"=>"New Value!"}
45 def update(other_hash
)
46 other_hash
.each_pair
{ |key
, value
| regular_writer(convert_key(key
), convert_value(value
)) }
50 alias_method
:merge!, :update
52 # Checks the hash for a key matching the argument passed in:
54 # hash = HashWithIndifferentAccess.new
55 # hash["key"] = "value"
56 # hash.key? :key # => true
57 # hash.key? "key" # => true
60 super(convert_key(key
))
63 alias_method
:include?, :key?
64 alias_method
:has_key?, :key?
65 alias_method
:member?, :key?
67 # Fetches the value for the specified key, same as doing hash[key]
68 def fetch(key
, *extras
)
69 super(convert_key(key
), *extras
)
72 # Returns an array of the values at the specified indices:
74 # hash = HashWithIndifferentAccess.new
77 # hash.values_at("a", "b") # => ["x", "y"]
79 def values_at(*indices
)
80 indices
.collect
{|key
| self[convert_key(key
)]}
83 # Returns an exact copy of the hash.
85 HashWithIndifferentAccess
.new(self)
88 # Merges the instantized and the specified hashes together, giving precedence to the values from the second hash
89 # Does not overwrite the existing hash.
94 # Removes a specified key from the hash.
96 super(convert_key(key
))
99 def stringify_keys
!; self end
100 def symbolize_keys
!; self end
101 def to_options
!; self end
103 # Convert to a Hash with String keys.
105 Hash
.new(default
).merge(self)
110 key
.kind_of
?(Symbol
) ? key
.to_s
: key
113 def convert_value(value
)
116 value
.with_indifferent_access
118 value
.collect
{ |e
| e
.is_a
?(Hash
) ? e
.with_indifferent_access
: e
}
125 module ActiveSupport
#:nodoc:
126 module CoreExtensions
#:nodoc:
128 module IndifferentAccess
#:nodoc:
129 def with_indifferent_access
130 hash
= HashWithIndifferentAccess
.new(self)
131 hash
.default
= self.default