Ruby Prepend Module - 如何从父类将模块添加到祖先数组的开头

P. *_*oro 2 ruby ruby-on-rails

我有这样的代码:

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
Run Code Online (Sandbox Code Playgroud)

我正在寻找在每次Child.new.perform调用之前打印方法参数的解决方案。我想ModuleToPrepend在 class 中祖先列表的开头添加一个模块Base。我不想把它放在一个类中,Child因为有数百个。

我的代码返回这个:Child.ancestrors #=> [Child, ModuleToPrepend, Base] 我想要这个:Child.ancestrors #=> [ModuleToPrepend, Child, Base]

可以在 ruby​​ 中完成吗?

Jay*_*rio 5

不确定这是否有任何副作用(如果有人,请赐教),但以下应该有效:

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
Run Code Online (Sandbox Code Playgroud)