Skip to content

Instantly share code, notes, and snippets.

@FaviusTy
Last active October 8, 2015 04:58
Show Gist options
  • Save FaviusTy/3280910 to your computer and use it in GitHub Desktop.
Save FaviusTy/3280910 to your computer and use it in GitHub Desktop.
単品で動くテストコードを追加
#encoding: utf-8
require 'ostruct'
# OpenStructを拡張
# Value以下ネストされたHashも全てOpenStructインスタンスとして展開します
class NestedOpenStruct < OpenStruct
def initialize(hash=nil)
@table = {}
if hash
for k, v in hash
@table[k.to_sym] = v.instance_of?(Hash) ? NestedOpenStruct.new(v) : v
new_ostruct_member(k)
end
end
end
# 現在のインスタンスの情報を全てHashインスタンス化して返します
# ネストされているNestedOpenStructは再帰的にこのメソッドによってHashに置き換わります
def to_hash
result_hash = @table.dup
result_hash.each_key{|key|
value = result_hash[key]
result_hash[key] = value.to_hash if value.instance_of? NestedOpenStruct
}
end
end
if __FILE__ == $0
test = {
string: "test",
num: 100,
arr: [1,2,3,4,5],
nested: {key: "key", value: "value"}
}
ostruct = NestedOpenStruct.new(test)
p "string: #{ostruct.string}, num: #{ostruct.num}, arr: #{ostruct.arr}, nested: #{ostruct.nested}"
p "nested.value: #{ostruct.nested.value}"
ostruct.string = "new_value"
p "string: #{ostruct.string}"
ostruct.add_field = "add"
p "add_field: #{ostruct.add_field}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment