Generator の歩き方を参考にrailsのscript/generateのソースを眺めていると、
アクションを登録するやり方が面白い。method_missing() を使って一行で処理している。Ruby の面目躍如だ。
という記述が。何ですと!?で、Rubyリファレンスを見てみる。
method_missing(name, args, ... )
呼びだされたメソッドが定義されていなかった時、Ruby がこのメソッドを呼び出します。
なるほど。で、早速自分で試してみる。
class Foo def initialize @actions = [] end def method_missing(action, *args, &block) @actions << [action, args, block] end def action(target) @actions.each do |action, arg, block| target.send(action, *arg, &block) end end end class Bar def hello(arg) print "hello, #{arg}\n" end def block_test(&block) yield end end foo = Foo.new foo.hello 'world' foo.block_test do print "block!!!\n" end foo.action Bar.new
実行結果。
$ ruby method_missing_test.rb hello, world block!!!
ほー、こんなこともできるんだ。おもしれー。(Ruby初心者まるだし)
追記。yieldの書き方が間違ってた・・・。orz