在类定义末尾执行 mixin 方法
我有一个混合,它反映接收器类以生成一些代码。这意味着我需要在类定义的末尾执行类方法,就像在这个简单的示例中一样:
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
添加到 mixin 中的 self.included
中,但这不起作用,因为我希望它反映的方法尚未被添加尚未宣布。我可以在课程结束时调用 include PrintMethods
,但这感觉不太好。
是否有任何技巧可以实现这一点,这样我就不需要在类定义末尾调用print_methods
?
I have a Mix-in that reflects on the receiver class to generate some code. This means that I need to execute the class method at the end of the class definition, like in this trivially dumbed down example:
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
I'd like to have the mixin do this for me automatically, but I can't come up with a way. My first thought was to add receiver.print_methods
to self.included
in the mixin, but that won't work because the method that I want it to reflect on has not been declared yet. I could call include PrintMethods
at the end of the class, but that feels like bad form.
Are there any tricks to make this happen so I don't need to call print_methods
at the end of the class definition?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,类的定义是没有尽头的。请记住,在 Ruby 中,您可以在“初始化”Tester 类方法后重新打开它,因此解释器无法知道该类“结束”的位置。
我能想到的解决方案是通过一些辅助方法来创建类,例如
但是必须以这种方式定义类肯定会让我的眼睛受伤。
First of all, there's no end of class definition. Remember that in Ruby you can reopen the Tester class method after you have 'initialized' it, so the interpreter can't know where the class 'ends'.
The solution I can come up with is to make the class via some helper method, like
But certainly having to define classes this way makes my eyes hurt.