我有这样的代码:
module ModuleToPrepend
def perform(*args)
puts args
super
end
end
class Base
prepend ModuleToPrepend
end
class Child < Base
def perform(*args)
do_something(args)
end
end
我正在寻找一种在每次 Child.new.perform
调用之前打印方法参数的解决方案。我想将模块 ModuleToPrepend
添加到类 Base
内祖先列表的开头。我不想将其添加到 Child
类中,因为它们有数百个。
我的代码返回:Child.ancestrors #=> [Child, ModuleToPrepend, Base]
我想要这个: Child.ancestrors #=> [ModuleToPrepend, Child, Base]
可以用 ruby 完成吗?
最佳答案
不确定这是否有任何副作用(如果有的话,请赐教),但以下应该有效:
module ModuleToPrepend
def perform(*args)
puts 'ModuleToPrepend#perform'
puts args
super
end
end
class Base
def self.inherited(subclass)
puts 'Base.inherited'
subclass.prepend(ModuleToPrepend) if subclass.superclass == Base
super
end
end
class Child < Base
def perform(*args)
puts 'Child#perform'
end
end
# => Base.inherited
class Subchild < Child
def perform(*args)
puts 'Subchild#perform'
super
end
end
# => Base.inherited
puts Child.ancestors
# => [ModuleToPrepend, Child, Base, Object, Kernel, BasicObject]
child = Child.new
child.perform('arg1', 'arg2')
# => ModuleToPrepend#perform
# => [arg1, arg2]
# => Child#perform
puts Subchild.ancestors
# => [Subchild, ModuleToPrepend, Child, Base, Object, Kernel, BasicObject]
subchild = Subchild.new
subchild.perform('arg1', 'arg2')
# => Subchild#perform
# => ModuleToPrepend#perform
# => [arg1, arg2]
# => Child#perform
关于ruby-on-rails - Ruby Prepend Module - 如何将模块添加到父类的祖先数组的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49897647/