YAMLから読み込んだ設定値(ハッシュ)をメソッドでアクセスするような目的で再帰的にした.
ちょっと思いついたので書いてみたが...ハッシュのインスタンスメソッドである必要はないかも...
Hash#structuralizeも考えたが,打鍵数が短いこともあってHash#to_structにした.
module CoreExtensions
module Hash
module Conversions
def to_struct(recursively = true)
if recursively
return inject({}) { |result, (key, value)|
if value.respond_to?(:to_struct)
value = value.to_struct
end
result[key] = value
result
}.to_struct(false)
else
k = keys
result_class = Struct.new(nil, *k.collect { |key| key.to_sym })
return result_class.new(*k.collect { |key| self[key] })
end
end
end
end
end
class Hash
include CoreExtensions::Hash::Conversions
end
if __FILE__ == $0
require "test/unit"
class HashToStructTest < Test::Unit::TestCase
def test_to_struct__recursive
o = {
"abc" => 10,
:def => "ghi",
"jkl" => {
:mno => true,
"10" => false,
},
}.to_struct
assert_equal(10, o.abc)
assert_equal("ghi", o.def)
assert_equal(true, o.jkl.mno)
assert_equal(false, o.jkl["10"])
end
def test_to_struct__not_recursive
base = {
"abc" => 10,
:def => "ghi",
"jkl" => {
:mno => true,
"10" => false,
},
}
o = base.to_struct(false)
assert_equal(10, o.abc)
assert_equal("ghi", o.def)
assert_raise(NoMethodError) do
assert_equal(true, o.jkl.mno)
end
assert_equal(base["jkl"], o.jkl)
end
end
end
Debian | LOOX T70HN | Linux | Rails | Rast | Ruby | TYPE T VGN-TZ90HS | boat | hardware | music | p | snowboard | software | surfing | tDiary | その他 | ボウリング | 映画 | 家族 | 会社 | 管理 | 丸藤 | 高専 | 散歩 | 仕事 | 自分 | 鼕
"Yuya.Nishida." / 西田 雄也 <yuya at j96 dot org>