-
-
Save makevoid/d9154bfaa1a5bec469039ac9f7afdd10 to your computer and use it in GitHub Desktop.
Recursively symbolize ruby hash keys in a nested structure. Uses refinements instead of monkey patching Hash.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# # usage: | |
# require_relative 'lib/stringify_helper' | |
# extend StringifyHelper | |
# using StringifyHelper | |
# | |
# { test: { foo: "bar" } }.deep_stringify_keys #=> \ | |
# # { "test" => { "foo" => "bar" } } | |
module StringifyHelper | |
extend self | |
def stringify_recursive(hash) | |
{}.tap do |h| | |
hash.transform_keys(&:to_s).each do |key, value| | |
value = case value | |
when Hash then stringify_recursive value | |
when Array then value.map { |elem| elem.is_a?(Hash) ? stringify_recursive(elem) : elem } | |
else | |
value | |
end | |
h[key] = value | |
end | |
end | |
end | |
refine Hash do | |
def deep_stringify_keys | |
StringifyHelper.stringify_recursive self | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment