-
-
Save apeiros/0a7b84f190ab2862136988002ea6bf86 to your computer and use it in GitHub Desktop.
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
module ToHash | |
def to_recursive_hash | |
case self | |
when Hash | |
each_with_object({}) { |(k,v), h| h[k.to_sym] = v.to_recursive_hash } | |
when Struct, OpenStruct | |
to_h.each_with_object({}) { |(k,v), h| h[k.to_sym] = v.to_recursive_hash } | |
when Array | |
map(&:to_recursive_hash) | |
else | |
respond_to?(:to_h) ? to_h : self | |
end | |
end | |
end | |
OpenStruct.send(:include, ToHash) | |
Struct.send(:include, ToHash) | |
Hash.send(:include, ToHash) | |
Object.send(:include, ToHash) |
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
module ToHash | |
module_function def convert_recursively(value) | |
case value | |
when Hash | |
value.each_with_object({}) { |(k,v), h| h[k.to_sym] = convert_recursively(v) } | |
when Struct, OpenStruct | |
value.to_h.each_with_object({}) { |(k,v), h| h[k.to_sym] = convert_recursively(v) } | |
when Array | |
value.map { |v| convert_recursively(v) } | |
else | |
value.respond_to?(:to_h) ? convert_recursively(value.to_h) : value | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment