Skip to content

Instantly share code, notes, and snippets.

@victorpolko
Last active September 8, 2015 15:06
Show Gist options
  • Save victorpolko/9fe0ec207f850fd6b223 to your computer and use it in GitHub Desktop.
Save victorpolko/9fe0ec207f850fd6b223 to your computer and use it in GitHub Desktop.
Ruby: deep OpenStruct with hash table
class DeepStruct < OpenStruct
def initialize(hash = nil)
check_hash = lambda { |entry| entry.is_a?(Hash) ? self.class.new(entry) : entry }
@table = {}
@hash_table = {}
hash.try(:each) do |key, val|
if val.is_a?(Array)
other = Array.new
val.each do |entry|
other.push check_hash.yield(entry)
end
val = other
end
@table[key.underscore.to_sym] = check_hash.yield(val)
@hash_table[key.underscore.to_sym] = val
new_ostruct_member(key)
end
end
def to_h
@hash_table
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment