1

レシーバークラスを反映してコードを生成するミックスインがあります。これは、次の単純な例のように、クラス定義の最後でクラス メソッドを実行する必要があることを意味します。

module PrintMethods
  module ClassMethods
    def print_methods
      puts instance_methods
    end
  end

  def self.included(receiver)
    receiver.extend ClassMethods
  end
end

class Tester
  include PrintMethods

  def method_that_needs_to_print
  end

  print_methods
end

ミックスインにこれ​​を自動的に実行してもらいたいのですが、方法が思いつきません。私の最初の考えは、ミックスインに追加receiver.print_methodsするself.includedことでしたが、それを反映させたいメソッドがまだ宣言されていないため、機能しません。クラスの最後に電話include PrintMethodsすることもできましたが、それは悪い形のように感じます.

print_methodsクラス定義の最後に呼び出す必要がないように、これを実現するためのトリックはありますか?

4

1 に答える 1

2

まず、クラスの定義に終わりはありません。Ruby では、テスター クラス メソッドを「初期化」した後で再度開くことができるため、インタープリターはクラスの「終了」場所を認識できないことに注意してください。

私が思いつく解決策は、次のようなヘルパーメソッドを介してクラスを作成することです

module PrintMethods
  module ClassMethods
    def print_methods
      puts instance_methods
    end
  end

  def self.included(receiver)
    receiver.extend ClassMethods
  end
end

class Object
  def create_class_and_print(&block)
    klass = Class.new(&block)
    klass.send :include, PrintMethods
    klass.print_methods
    klass
  end
end

Tester = create_class_and_print do
  def method_that_needs_to_print
  end
end

しかし、確かにこのようにクラスを定義しなければならないことは私の目を痛めます。

于 2010-07-04T19:42:17.397 に答える