From a4bb195c91fa9bb25e136aa8850f3acafea0a597 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lucas=20H=C3=BAngaro?= Date: Sun, 29 Apr 2012 15:43:06 -0300 Subject: Adding deep versions of stringify_keys and symbolize_keys (plain and bang) for nested hashes --- .../lib/active_support/core_ext/hash/keys.rb | 44 ++++++++++++++++++++++ 1 file changed, 44 insertions(+) (limited to 'activesupport/lib/active_support/core_ext') 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 -- cgit v1.2.3