Skip to content

Instantly share code, notes, and snippets.

@quanon
Created January 29, 2015 06:41
Show Gist options
  • Select an option

  • Save quanon/2c1498e147f7e8883774 to your computer and use it in GitHub Desktop.

Select an option

Save quanon/2c1498e147f7e8883774 to your computer and use it in GitHub Desktop.
YAML.load した結果に含まれる Hash を Struct に変換する。
# 使い方:
# yml = File.read(path)
# yml_to_struct(yml)
def yml_to_struct(yml)
yml_object = YAML.load(ERB.new(yml).result)
yml_object_to_struct(yml_object)
end
# YAML.load した結果の Object に含まれる Hash を Struct に変換し、
# より直感的にアクセスできるようにする。
# (参考) アクセサが好きならばハッシュよりも構造体がよい
# http://d.hatena.ne.jp/rubikitch/20080819/1219082601
def yml_object_to_struct(yml_object)
call_me = -> (value) { send(__method__, value) }
case yml_object
when Array
yml_object.map(&call_me)
when Hash
keys = yml_object.keys.map(&:to_sym)
values = yml_object.values.map(&call_me)
Struct.new(*keys).new(*values)
else
yml_object
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment