Last active
May 22, 2020 04:17
-
-
Save edvardm/9639051 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 hidden or 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
module SymbolizeHelper | |
extend self | |
def symbolize_recursive(hash) | |
{}.tap do |h| | |
hash.each { |key, value| h[key.to_sym] = transform(value) } | |
end | |
end | |
private | |
def transform(thing) | |
case thing | |
when Hash; symbolize_recursive(thing) | |
when Array; thing.map { |v| transform(v) } | |
else; thing | |
end | |
end | |
refine Hash do | |
def deep_symbolize_keys | |
SymbolizeHelper.symbolize_recursive(self) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Like deep_symbolize_keys in Rails, with the addition of symbolizing hashes in nested arrays.