sendとmethod_missingをつかって委譲(丸投げ)するクラスを作ってみた。
Adapterパターンとかが簡単に出来そうだ。
丸投げクラス
class Marunage
def initialize(target, map = {})
@target = target
@map = map
end
def method_missing(method, *args, &block)
target_method = @map[method]
unless target_method
target_method = method
end
@target.send(target_method, *args, &block)
end
end
- コンストラクタ
- 丸投げ先のオブジェクト
- 丸投げ時のメソッドの関連付けマップ
- method_missing
- 丸投げ時の関連付けマップから丸投げ先のメソッドを探す
- 丸投げ時の関連付けが無かったら同じ名前のメソッドを呼ぶようにする
- 丸投げ先のメソッドを呼ぶ
こんな流れ。
実際に使うときは以下のようになる
# say_helloメソッドが呼ばれたら,print_helloに丸投げする
m = Marunage.new(Printer.new, {:say_hello => :print_hello})
# さぁ!丸投げしてくれ!
m.say_hello実行結果
Hello world
丸投げ成功〜!