-
-
Save brodock/fb2167d61154d9158196 to your computer and use it in GitHub Desktop.
json to struct
This file contains hidden or 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
require 'ostruct' | |
class JsonStruct < OpenStruct | |
def initialize(hash = nil) | |
@table = {} | |
@hash_table = {} | |
return unless hash | |
hash.each do |k, v| | |
recursive_initializer(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 recursive_initializer(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