Skip to content

Instantly share code, notes, and snippets.

@apeiros
Last active May 25, 2016 15:20
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 apeiros/0a7b84f190ab2862136988002ea6bf86 to your computer and use it in GitHub Desktop.
Save apeiros/0a7b84f190ab2862136988002ea6bf86 to your computer and use it in GitHub Desktop.
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)
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