Added IndifferentAccess as a way to wrap a hash by a symbol-based store that...

Added IndifferentAccess as a way to wrap a hash by a symbol-based store that also can be accessed by string keys

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@581 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
上级 e505a451
*SVN*
* Fixed double requiring of models with the same name as the controller
* Fixed that query params could be forced to nil on a POST due to the raw post fix #562 [moriq@moriq.com]
* Fixed that cookies shouldn't be frozen in TestRequest #571 [Eric Hodel]
......
* Added IndifferentAccess as a way to wrap a hash by a symbol-based store that also can be accessed by string keys
* Added Inflector.humanize to turn attribute names like employee_salary into "Employee salary". Used by automated error reporting in AR.
* Added availability of class inheritable attributes to the masses #477 [bitsweat]
......
require File.dirname(__FILE__) + '/hash/keys'
require File.dirname(__FILE__) + '/hash/indifferent_access'
class Hash #:nodoc:
include ActiveSupport::CoreExtensions::Hash::Keys
include ActiveSupport::CoreExtensions::Hash::IndifferentAccess
end
class HashWithIndifferentAccess < Hash
def initialize(constructor)
if constructor.is_a?(Hash)
super()
update(constructor.symbolize_keys)
else
super(constructor)
end
end
alias_method :regular_read, :[]
def [](key)
case key
when Symbol: regular_read(key) || regular_read(key.to_s)
when String: regular_read(key) || regular_read(key.to_sym)
else regular_read(key)
end
end
alias_method :regular_writer, :[]=
def []=(key, value)
regular_writer(key.is_a?(String) ? key.to_sym : key, value)
end
end
module ActiveSupport #:nodoc:
module CoreExtensions #:nodoc:
module Hash #:nodoc:
module IndifferentAccess
def with_indifferent_access
HashWithIndifferentAccess.new(self)
end
end
end
end
end
......@@ -2,7 +2,6 @@ module ActiveSupport #:nodoc:
module CoreExtensions #:nodoc:
module Hash #:nodoc:
module Keys
# Return a new hash with all keys converted to symbols.
def symbolize_keys
inject({}) do |options, (key, value)|
......
......@@ -2,7 +2,6 @@
require File.dirname(__FILE__) + '/../../lib/core_ext/hash'
class HashExtTest < Test::Unit::TestCase
def setup
@strings = { 'a' => 1, 'b' => 2 }
@symbols = { :a => 1, :b => 2 }
......@@ -33,6 +32,17 @@ def test_symbolize_keys!
assert_raises(NoMethodError) { { [] => 1 }.symbolize_keys! }
end
def test_indifferent_access
@strings = @strings.with_indifferent_access
@symbols = @symbols.with_indifferent_access
@mixed = @mixed.with_indifferent_access
assert_equal @strings[:a], @strings["a"]
assert_equal @symbols[:a], @symbols["a"]
assert_equal @strings["b"], @mixed["b"]
assert_equal @strings[:b], @mixed["b"]
end
def test_assert_valid_keys
assert_nothing_raised do
{ :failure => "stuff", :funny => "business" }.assert_valid_keys([ :failure, :funny ])
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册