私はいくつかのメソッドを持つクラスを持っています。supersekret ですが、ここでできることを再現しました。
Class RayGun
# flashes red light
# requires confirmation
# makes "zowowowowowow" sound
def stun!
# ...
end
# flashes blue light
# does not require confirmation
# makes "trrrtrtrtrrtrtrtrtrtrtr" sound
def freeze!
# ...
end
# doesn't flash any lights
# does not require confirmation
# makes Windows startup sound
def killoblast!
# ...
end
end
実行時に、メソッドの 1 つについてクラスに問い合わせて、次のようにハッシュまたは構造体を受け取ることができるようにしたいと考えています。
{:lights => 'red', :confirmation => false, :sound => 'windows'}
これを行う最善の方法は何ですか?もちろん、別々の YAML ファイルを横に置いて、2 つを関連付ける規則を設定することもできますが、コードとメタデータを 1 か所にまとめることが理想的です。
私が思いつく最も有望なアイデアは、次のようなものです。
class RayGun
cattr_accessor :metadata
def self.register_method(hsh)
define_method(hsh.name, hsh.block)
metadata[hsh[:name]] = hsh
end
register_method({
:name => 'stun!',
:lights => 'red',
:confirmation => 'true',
:sound => 'zowowo',
:block => Proc.new do
# code goes here
})
# etc.
end
誰かがより良いアイデアを持っていますか?私は非常に間違った木を吠えていますか?