我正在看一个模块X,它包含两个名为“InstanceMethods
“和”ClassMethods
”。
模块X中的最后一个定义是:
def self.included(base)
base.send :include, InstanceMethods
base.send :extend, ClassMethods
end
这是做什么的?
我正在看一个模块X,它包含两个名为“InstanceMethods
“和”ClassMethods
”。
模块X中的最后一个定义是:
def self.included(base)
base.send :include, InstanceMethods
base.send :extend, ClassMethods
end
这是做什么的?
included
只要模块包含在另一个模块或类中,就会调用它。在这种情况下,它将尝试调用 base
的 include
从中获取模块方法,变量和常量的方法 InstanceMethods
加入 base
然后会尝试调用 base
的 extend
从中获取实例方法的方法 ClassMethods
添加到 base
。
它也可能是
def self.included( base )
base.include( InstanceMethods )
base.extend( ClassMethods )
end
'send'调用它的第一个参数作为调用它的对象的方法,其余的参数作为参数发送给方法。所以在这种情况下,
base.send :include, InstanceMethods
相当于
base.include(InstanceMethods)
这将InstanceMethods模块中的方法添加到“基础”对象
它定义了一个带有参数的类方法“base
“然后它会调用 include
和 extend
方法 base
,传递模块 InstanceMethods
和 ClassMethods
分别作为论据。打电话给 include
将添加定义的实例方法 InstanceMethods
至 base
。我不熟悉 extend
方法,但我认为它也会做类似的事情,但对于类方法。