Skip to content

Instantly share code, notes, and snippets.

@makevoid
Forked from edvardm/symbolize_recursive.rb
Last active May 22, 2020 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save makevoid/d9154bfaa1a5bec469039ac9f7afdd10 to your computer and use it in GitHub Desktop.
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.
# # 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