运行此代码:
module A
def self.included(klass)
klass.send(:cattr_accessor, :my_name)
end
def set_my_name_var
@@my_name = 'A' # does NOT work as expected
end
def set_my_name_attr
self.class.my_name = 'A' # works as expected
end
end
class B
include A
cattr_accessor :my_other_name
def set_my_other_name_var
@@my_other_name = 'B' # works
end
def set_my_other_name_attr
self.class.my_other_name = 'B' # works
end
end
b = B.new
b.set_my_other_name_var
puts "My other name is " + B.my_other_name
b.set_my_name_var
puts "My name is " + B.my_name
b.set_my_other_name_attr
puts "My other name is " + B.my_other_name
b.set_my_name_attr
puts "My name is " + B.my_name
像这样中断:
My other name is B
TypeError: (eval):34:in `+': can't convert nil into String
如果我们交换最后两个代码块(以便b.set_my_name_attr
在之前调用b.set_my_name_var
),一切正常。
看起来它被视为@@my_name
模块的类变量A
,而不是类B
(正如我所期望的那样)。不是很混乱吗?在哪里可以阅读有关模块类变量的更多信息?