简体   繁体   English

如何在ruby中调用一系列模块中定义的超级方法

[英]How to call super methods defined in a serial of modules in ruby

Is it possible to make c1.say to show "lalala" without changing M1, M2, C1? 有没有可能让c1.say显示“lalala”而不改变M1,M2,C1? Ie, use extra modules to override M2's method? 即,使用额外的模块来覆盖M2的方法? Thanks, 谢谢,

module M1
  def word
    "lalala"
  end
end

module M2
  def word
    super + 'wawawa'
  end
end

class C1
  include M1
  include M2
  def say
    puts word
  end
end

c1 = C1.new
c1.say # lalalawawawa

You can always monkey-patch any class without changing its original code. 您可以随时修改任何类,而无需更改其原始代码。

module M1
  def word
    "lalala"
  end
end

module M2
  def word
    super + 'wawawa'
  end
end

class C1
  include M1
  include M2
  def say
    puts word
  end
end

# patch M2
M2.class_eval do
  def word
    super
  end
end

# or patch C1
# C1.class_eval do
#   def word
#     'lalala'
#   end
# end


c1 = C1.new
c1.say
# >> lalala

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM