代码如下:
module ModuleDemo
def self.included(mod)
puts "#{self} is included in #{mod}"
end
def self.append_features(mod)
puts "#{mod} append_features by #{self}"
end
end
class ClassDemo
include ModuleDemo
end
代码输出 #
ClassDemo append_features by ModuleDemo
ModuleDemo is included in ClassDemo
问题 1:included 是 hook methods,也是 Module 的私有实例方法,按照元编程的思想,私有实例变量不能被显示调用,是否与这里的 self.included 相悖。 问题 2:hook methods 方法被重写的时候,一般都是 self.included 形式,这样子有什么讲究?为什么不能是如下的形式:
module ModuleDemo
#当然include的时候是无效的
def included(mod)
puts "puts something"
end
end
问题 3:included 方法在 api 中文档说明为:Callback invoked whenever the receiver is included in another module or class. This should be used in preference to Module.append_features. if your code wants to perform some action when a module is included in another. 其中英文 in preference to 应该是优先于的意思,我的理解是 included 优先于 append_features 执行,但是如上代码的执行情况,刚好相反,哪里出了问题? 问题 4:api 文档中只是给出了 included 方法作为 hook methods 被重写的情形,但是对于直接使用 included 未提及。比如下面的这段代码,included 的作用是什么?,included 的一般用法是什么?
module HairColors
extend ActiveSupport::Concern
included do
mattr_accessor :hair_colors
end
end
class Person
include HairColors
end
Person.hair_colors = [:brown, :black, :blonde, :red]
Person.hair_colors # => [:brown, :black, :blonde, :red]
Person.new.hair_colors # => [:brown, :black, :blonde, :red]
HairColors.hair_colors # => undefined method `hair_colors' for HairColors:Module