简体   繁体   English

Ruby:模块和超级?

[英]Ruby: modules and super?

I don't understand why this works. 我不明白为什么会这样。

module Base
  attr_reader :first
  def setup
    @first = 1
  end
end

module Addon
  attr_reader :second
  def setup
    #super
    @second = 2
  end
end

class Test
  include Base
  include Addon

  def initialize(num)
    @num = num
    setup
  end
end

a = Test.new(1)
p a.first
p a.second

Basically I have a "base" module, which sets up some stuff. 基本上我有一个“基础”模块,它设置了一些东西。 I also have an addon module, which sets up some more stuff if some class wants to include it. 我还有一个插件模块,如果某个类想要包含它,它会设置更多的东西。

Now when I test it, if I don't have that super call, I get 现在,当我测试它时,如果我没有那个超级电话,我会得到

nil
2

When I do have the super call, I get 当我有超级电话时,我明白了

1
2

What does super actually do here? 超级实际上在这做什么? It's calling the setup method from the Base module, even when Base and Addon are not related. 即使Base和Addon不相关,它也会从Base模块调用setup方法。

This is the first time I've used super in the context of modules. 这是我第一次在模块环境中使用super。 Previously I've always used super calls with classes and thought it was just going up the inheritance tree to find a parent with the same method. 以前我总是使用类的超级调用,并认为它只是继承树继续寻找具有相同方法的父级。

Is including multiple modules also setting up some sort of inheritance tree? 是否包含多个模块还设置了某种继承树?

EDIT: for context, the Addon module will never be included without the Base module, and the Base module will always be included before any additional Addon modules. 编辑:对于上下文,如果没有Base模块,将永远不会包含Addon模块,并且在任何其他Addon模块之前将始终包含Base模块。

Yes, when you include modules, they are injected into inheritance chain 是的,当您包含模块时,它们会被注入到继承链中

Test.ancestors # => [Test, Addon, Base, Object, Kernel, BasicObject]

Addon module, when included, redefines existing setup method from Base . Addon模块,当包括时,重新定义现有的setup从方法Base If you want Base 's version be called, use super . 如果你想要调用Base的版本,请使用super

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

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