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

我想让mixin自动为我做这件事,但我想不出办法。我的第一个想法是添加receiver.print_methodsself.includedmixin 中,但这不起作用,因为我希望它反映的方法尚未声明。我可以include PrintMethods在课程结束时打电话,但这感觉很糟糕。

是否有任何技巧可以实现这一点,所以我不需要print_methods在类定义的末尾调用?

4

1 回答 1

2

首先,类定义没有尽头。请记住,在 Ruby 中,您可以在“初始化”后重新打开 Tester 类方法,因此解释器无法知道类“结束”的位置。

我能想出的解决方案是通过一些辅助方法来创建类,比如

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 回答