Last active
September 8, 2015 15:06
-
-
Save victorpolko/9fe0ec207f850fd6b223 to your computer and use it in GitHub Desktop.
Ruby: deep OpenStruct with hash table
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
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