From: keiju@... (Keiju ISHITSUKA) Date: 1998-04-14T13:28:43+09:00 Subject: [ruby-dev:2305] MetaDelegator けいじゅ@日本ラショナルソフトウェアです. 次のようなモジュール(といっても小さいんだけど)を作りました. Deletgatorと機能的には似ているですが, 制約されたdelegatorを定義するも のです. module MetaDelegator def def_delegators(accessor, *methods) for method in methods def_delegator(accessor, method) end end def def_delegator(accessor, method, ali = method) accessor = methods.id2name if accessor.kind_of?(Integer) method = method.id2name if method.kind_of?(Integer) ali = ali.id2name if method.kind_of?(Integer) module_eval "def #{ali}(*args,&block); #{accessor}.__send__(:#{method}, *args,&block); end" end end 使い方は以下のような感じです. irb(main):001:0> load "meta-delegator.rb" true irb(main):002:0> class Foo irb(main):003:1> extend MetaDelegator irb(main):004:1> def_delegators("@out", "printf", "print") irb(main):005:1> def_delegators("@in", "gets") irb(main):006:1> end nil irb(main):007:0> Foo.instance_methods ["print", "gets", "printf"] irb(main):008:0> 上記のように, ある特定のメソッドに対してのみあるアクセサ(およびインス タンス変数)にメッセージを送ります. 使い道としては, 何でもかんでも委譲 するのではなく, 決められたものだけ委譲したい場合に利用できます. 私の感 覚としては, このように決められたものだけ委譲する方が利用価値が高いんじゃ ないかな? って気がしています. あと, Delegetorはインスタンス単位に特異メソッドを定義しますが, これは メソッドを直接定義します. そういう意味では, かなり静的なイメージですよ ね. そこで, 特異メソッドを定義する以下のモジュールも定義しました. module MetaSingletonDelegator def def_delegators(accessor, *methods) for method in methods def_delegator(accessor, method) end end def def_delegator(accessor, method, ali = method) accessor = methods.id2name if accessor.kind_of?(Integer) method = method.id2name if method.kind_of?(Integer) instance_eval "def #{method}(*args,&block); #{accessor}.__send__(:#{method}, *args,&block); end" end end irb(main):011:0> f = Foo.new # irb(main):012:0> load "meta-delegator.rb" true irb(main):013:0> f.extend MetaSingletonDelegator # irb(main):026:0> f.def_delegator("@contents", "[]") nil irb(main):027:0> f.singleton_methods ["[]"] まあ, こういう使い方はあまりしないと思いますが, クラスメソッドの定義に は利用できるかも知れません. 一応, in.comingに meta-delegator.rb として置きますが, delegator.rbに統 合した方が良いかも知れません. __ ..............................石塚 圭樹@日本ラショナルソフトウェア... ----------------------------------->> e-mail: keiju@rational.com <<---