我有这样的代码:

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
可以用红宝石做吗?

最佳答案

不确定这是否有任何副作用(如果有,请告诉我),但以下方法应该有效:

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

10-08 08:18
查看更多