aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext
diff options
context:
space:
mode:
authorCarlos Antonio da Silva <carlosantoniodasilva@gmail.com>2012-05-23 09:19:56 -0700
committerCarlos Antonio da Silva <carlosantoniodasilva@gmail.com>2012-05-23 09:19:56 -0700
commit541429fbe49b0671adb3842ab1818230d670ef9f (patch)
tree64a71bae017ae2a6d5fc701eff2dfd8e57b05cd0 /activesupport/lib/active_support/core_ext
parentc1487f619045840d89f1e2dbc6e133e1c2cbf2f4 (diff)
parenta4bb195c91fa9bb25e136aa8850f3acafea0a597 (diff)
downloadrails-541429fbe49b0671adb3842ab1818230d670ef9f.tar.gz
rails-541429fbe49b0671adb3842ab1818230d670ef9f.tar.bz2
rails-541429fbe49b0671adb3842ab1818230d670ef9f.zip
Merge pull request #6060 from lucashungaro/master
Adding deep versions of stringify_keys and symbolize_keys (plain and bang) for nested hashes
Diffstat (limited to 'activesupport/lib/active_support/core_ext')
-rw-r--r--activesupport/lib/active_support/core_ext/hash/keys.rb44
1 files changed, 44 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/core_ext/hash/keys.rb b/activesupport/lib/active_support/core_ext/hash/keys.rb
index 8b24ef3350..5eb861934d 100644
--- a/activesupport/lib/active_support/core_ext/hash/keys.rb
+++ b/activesupport/lib/active_support/core_ext/hash/keys.rb
@@ -64,4 +64,48 @@ class Hash
raise ArgumentError.new("Unknown key: #{k}") unless valid_keys.include?(k)
end
end
+
+ # Return a new hash with all keys converted to strings.
+ # This includes the keys from the root hash and from all
+ # nested hashes.
+ def deep_stringify_keys
+ result = {}
+ each do |key, value|
+ result[key.to_s] = value.is_a?(Hash) ? value.deep_stringify_keys : value
+ end
+ result
+ end
+
+ # Destructively convert all keys to strings.
+ # This includes the keys from the root hash and from all
+ # nested hashes.
+ def deep_stringify_keys!
+ keys.each do |key|
+ val = delete(key)
+ self[key.to_s] = val.is_a?(Hash) ? val.deep_stringify_keys! : val
+ end
+ self
+ end
+
+ # Destructively convert all keys to symbols, as long as they respond
+ # to +to_sym+. This includes the keys from the root hash and from all
+ # nested hashes.
+ def deep_symbolize_keys!
+ keys.each do |key|
+ val = delete(key)
+ self[(key.to_sym rescue key)] = val.is_a?(Hash) ? val.deep_stringify_keys! : val
+ end
+ self
+ end
+
+ # Return a new hash with all keys converted to symbols, as long as
+ # they respond to +to_sym+. This includes the keys from the root hash
+ # and from all nested hashes.
+ def deep_symbolize_keys
+ result = {}
+ each do |key, value|
+ result[(key.to_sym rescue key)] = value.is_a?(Hash) ? value.deep_symbolize_keys : value
+ end
+ result
+ end
end