结合《Ruby 元编程》的例子写了如下代码,有几点疑问,感谢解答:
module Concern
def self.extended(base)
p "extended:self=#{self},base=#{base}"
base.instance_variable_set(:@_dependencies, [])
end
def append_features(base)
if base.instance_variable_defined?(:@_dependencies)
base.instance_variable_get(:@_dependencies) << self
p "if:self=#{self},base=#{base},@=#{base.instance_variable_get(:@_dependencies)}"
return false
else
return false if base < self
p "else:self=#{self},@_dependencies=#{@_dependencies}"
@_dependencies.each { |dep| base.include(dep) }
super
base.extend const_get(:ClassMethods) if const_defined?(:ClassMethods)
end
end
end
module Myc2
extend Concern
def m3
p "Myc2 instance method"
end
module ClassMethods
def m4
p "Myc2 class method"
end
end
end
module Myc1
extend Concern
include Myc2
def m1
p "Myc1 instance method"
end
module ClassMethods
def m2
p "Myc1 class method"
end
end
end
class Mytest
include Myc1
end
输出如下:
"extended:self=Concern,base=Myc2"
"extended:self=Concern,base=Myc1"
"if:self=Myc2,base=Myc1,@=[Myc2]"
"else:self=Myc1,@_dependencies=[Myc2]"
"else:self=Myc2,@_dependencies=[]"