Skip to content

Instantly share code, notes, and snippets.

@xiy
Forked from brodock/deep_struct.rb
Last active May 11, 2016 10:36
Show Gist options
  • Save xiy/366c3a237eee8f38cb835b64e949333b to your computer and use it in GitHub Desktop.
Save xiy/366c3a237eee8f38cb835b64e949333b to your computer and use it in GitHub Desktop.
Hash to Struct
require 'ostruct'
class DeepStruct < OpenStruct
def initialize(hash = {})
@table = {}
@hash_table = {}
hash.each do |k, v|
recrusively_initialize(v) if v.is_a?(Array)
@table[k.to_sym] = (v.is_a?(Hash) ? self.class.new(v) : v)
@hash_table[k.to_sym] = v
new_ostruct_member(k)
end
end
def to_h
@hash_table
end
protected
def recursively_initialize(item)
item.collect! do |val|
if val.is_a?(Hash)
self.class.new(val)
elsif val.is_a?(Array)
recurse.call(val)
else
val
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment