【发布时间】:2011-03-11 16:03:57
【问题描述】:
我有一个混入,它反映在接收器类上以生成一些代码。这意味着我需要在类定义的末尾执行类方法,就像在这个简单的例子中一样:
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 自动为我做这件事,但我想不出办法。我的第一个想法是在 mixin 中将 receiver.print_methods 添加到 self.included 中,但这不起作用,因为我希望它反映的方法尚未声明。我可以在课程结束时打电话给include PrintMethods,但这感觉很糟糕。
是否有任何技巧可以做到这一点,所以我不需要在类定义的末尾调用print_methods?
【问题讨论】: