mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Added Hash#stringify_keys and Hash#stringify_keys!
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@586 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
This commit is contained in:
parent
61a6a440cb
commit
83c3f6f81a
3 changed files with 35 additions and 0 deletions
|
@ -1,3 +1,5 @@
|
|||
* Added Hash#stringify_keys and Hash#stringify_keys!
|
||||
|
||||
* 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.
|
||||
|
|
|
@ -2,6 +2,25 @@ module ActiveSupport #:nodoc:
|
|||
module CoreExtensions #:nodoc:
|
||||
module Hash #:nodoc:
|
||||
module Keys
|
||||
# Return a new hash with all keys converted to strings.
|
||||
def stringify_keys
|
||||
inject({}) do |options, (key, value)|
|
||||
options[key.to_s] = value
|
||||
options
|
||||
end
|
||||
end
|
||||
|
||||
# Destructively convert all keys to strings.
|
||||
def stringify_keys!
|
||||
keys.each do |key|
|
||||
unless key.is_a?(String)
|
||||
self[key.to_s] = self[key]
|
||||
delete(key)
|
||||
end
|
||||
end
|
||||
self
|
||||
end
|
||||
|
||||
# Return a new hash with all keys converted to symbols.
|
||||
def symbolize_keys
|
||||
inject({}) do |options, (key, value)|
|
||||
|
|
|
@ -12,6 +12,8 @@ class HashExtTest < Test::Unit::TestCase
|
|||
h = {}
|
||||
assert_respond_to h, :symbolize_keys
|
||||
assert_respond_to h, :symbolize_keys!
|
||||
assert_respond_to h, :stringify_keys
|
||||
assert_respond_to h, :stringify_keys!
|
||||
assert_respond_to h, :to_options
|
||||
assert_respond_to h, :to_options!
|
||||
end
|
||||
|
@ -32,6 +34,18 @@ class HashExtTest < Test::Unit::TestCase
|
|||
assert_raises(NoMethodError) { { [] => 1 }.symbolize_keys! }
|
||||
end
|
||||
|
||||
def test_stringify_keys
|
||||
assert_equal @strings, @symbols.stringify_keys
|
||||
assert_equal @strings, @strings.stringify_keys
|
||||
assert_equal @strings, @mixed.stringify_keys
|
||||
end
|
||||
|
||||
def test_stringify_keys!
|
||||
assert_equal @strings, @symbols.dup.stringify_keys!
|
||||
assert_equal @strings, @strings.dup.stringify_keys!
|
||||
assert_equal @strings, @mixed.dup.stringify_keys!
|
||||
end
|
||||
|
||||
def test_indifferent_access
|
||||
@strings = @strings.with_indifferent_access
|
||||
@symbols = @symbols.with_indifferent_access
|
||||
|
|
Loading…
Reference in a new issue