在类定义的末尾执行mixin方法
我有一个Mix-in反映在接收器类上以生成一些代码。 这意味着我需要在类定义的最后执行类方法,就像在这个简单的愚蠢的例子中一样:
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_methods
添加到self.included
in mixin中,但这不起作用,因为我想要它反映的方法还没有被声明。 我可以在课程结束时调用include PrintMethods
,但感觉就像糟糕的forms。
是否有任何技巧可以实现这一点,所以我不需要在类定义的末尾调用print_methods
?
首先,课程定义没有结束。 请记住,在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
但当然必须以这种方式定义课程会让我的眼睛受伤。