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

时间:2018-04-18 10:40:36

标签: ruby-on-rails ruby

我有这样的代码:

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]

可以用红宝石完成吗?

1 个答案:

答案 0 :(得分:3)

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

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