问题 “base.send:include,InstanceMethods”--->这是做什么的?


我正在看一个模块X,它包含两个名为“InstanceMethods“和”ClassMethods”。

模块X中的最后一个定义是:

  def self.included(base)
    base.send :include, InstanceMethods
    base.send :extend,  ClassMethods
  end

这是做什么的?


9617
2018-06-10 04:11


起源

我知道这不是你的代码,但请注意,不需要InstanceMethod模块:父模块已经包含在内,所以我们应该将实例方法放在那里。 - tokland


答案:


included 只要模块包含在另一个模块或类中,就会调用它。在这种情况下,它将尝试调用 baseinclude 从中获取模块方法,变量和常量的方法 InstanceMethods 加入 base 然后会尝试调用 baseextend 从中获取实例方法的方法 ClassMethods 添加到 base

它也可能是

def self.included( base )
  base.include( InstanceMethods )
  base.extend( ClassMethods )
end

9
2018-06-10 04:28



好的,这是有道理的。有一个类W包含模块X,因此我们的想法是W通过这些模块获取X中包含的所有实例方法和类方法。缺少的部分是如何调用'包含' - 但是当你说“W包含X”时,你会说,将调用included()方法。 - 弗朗兹0秒前 - franz
那就对了。还有更多的信息和友好的例子 ruby-doc.org/core/classes/Module.html#M001683 - toholio
include是Method类的私有方法。因此,base.include将无效。 - Pedro Morte Rolo


'send'调用它的第一个参数作为调用它的对象的方法,其余的参数作为参数发送给方法。所以在这种情况下,

base.send :include, InstanceMethods

相当于

base.include(InstanceMethods)

这将InstanceMethods模块中的方法添加到“基础”对象


1
2018-06-10 04:21



它并不完全等同于 base.send :include 即使该方法已被私有,仍会调用include。 base.include 会引发错误。 - Oliver N.


它定义了一个带有参数的类方法“base“然后它会调用 include 和 extend 方法 base,传递模块 InstanceMethods 和 ClassMethods 分别作为论据。打电话给 include 将添加定义的实例方法 InstanceMethods 至 base。我不熟悉 extend 方法,但我认为它也会做类似的事情,但对于类方法。


0
2018-06-10 04:21