Skip to content

Instantly share code, notes, and snippets.

@alexanderk23
Created December 4, 2013 12:56
Show Gist options
  • Select an option

  • Save alexanderk23/7787043 to your computer and use it in GitHub Desktop.

Select an option

Save alexanderk23/7787043 to your computer and use it in GitHub Desktop.
DeepOpenStruct with recursive to_h
class DeepOpenStruct < OpenStruct
def to_h
convert_to_hash_recursive self.dup
end
def self.load item
raise ArgumentError, "DeepOpenStruct must be passed a Hash or Array" unless(item.is_a?(Hash) || item.is_a?(Array))
self.convert_from_hash_recursive item
end
private
def self.convert_from_hash_recursive obj
result = obj
case result
when Hash
result = result.dup
result.each do |k,v|
result[k] = convert_from_hash_recursive(v)
end
result = DeepOpenStruct.new result
when Array
result = result.map { |v| convert_from_hash_recursive(v) }
end
result
end
def convert_to_hash_recursive obj
result = obj
case result
when OpenStruct
result = result.marshal_dump
result.each do |k,v|
result[k] = convert_to_hash_recursive(v)
end
when Array
result = result.map { |v| convert_to_hash_recursive(v) }
end
result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment