method_missingで委譲

Rubyで簡単に委譲を行うには、普通標準添付のdelegate.rbを使うと思います。が、ここではmethod_missingを使って委譲を行うサンプルを紹介します。method_missingのよい使用例じゃないかな。

module MethodMissingDelegator
  def method_missing(mesg, *arg)
    @to_obj.send(mesg, *arg)
  end  
end

使い方。

class Foo
  def hello
    puts "#{self.class}: hello"
  end
end

class Hoge
  include MethodMissingDelegator
  def initialize
    # 自分が知らないメソッドは@to_objに委譲する。
    @to_obj = Foo.new
  end
end

Hoge.new.hello
# => Foo: hello

@to_objを定義しないといけないのがダサいですね(モジュールの実装がミエミエ)。
Rubyで委譲はほんと楽です。C++とかJavaは(いくらIDEの支援があっても)面倒すぎます。
参照: プログラミング言語 Ruby リファレンスマニュアル