在ruby中想讓class存儲(chǔ)變量有兩種方式林艘。
- class variable
- class instance variable
下面是用class variable的具體例子如下:
class P
@@v = 1
def self.v
@@v
end
def class_v
@@v
end
end
P.v #=> 1
P.new.class_v #=> 1
下面是用class instance variable的具體例子如下:
class P2
@v = 1
def self.v
@v
end
def class_v
self.class.v
end
end
P2.v #=> 1
P2.new.class_v #=> 1
從上面的例子來看好像基本上是實(shí)現(xiàn)了相同的功能。
相同點(diǎn)是都可以在class這個(gè)context下訪問梢杭,一個(gè)通過@@v
一個(gè)通過@v
儒旬。
不同點(diǎn)是class variable可以在普通的instance method中直接訪問栏账,而instance_variable是不可的,要調(diào)用self的class來訪問(不信你是試試直接訪問栈源,肯定不成挡爵,因?yàn)橹苯釉L問的意思是該context下self自己instance_variable)。
但是class variable是屬于類的層級(jí)關(guān)系的(class hierarchies)甚垦,也就是說@@v是可以被繼承的茶鹃,但不是copy一個(gè)而是link到最底層的那個(gè)。這樣的機(jī)制就會(huì)產(chǎn)生一些惡心的事情發(fā)生艰亮。代碼如下:
class T < P
@@v = 4
end
T.v #=> 4
P.v #=> 4
看出來了吧闭翩,這個(gè)不太是我們的想要的,把原來P的@v
的值都改變了迄埃。
那么instance variable怎么實(shí)現(xiàn)繼承呢疗韵。代碼如下:
class T2 < P2
@v = 8
end
T2.v #=> 8
P2.v #=> 1
看起來不錯(cuò),是我們想要的侄非。
但是在子類沒有@v
這個(gè)instance variable時(shí)蕉汪,會(huì)怎么樣呢?
class O < P2; end
puts O.sides # => nil
也就是說其實(shí)是沒有繼承的逞怨,那么我們想copy一個(gè)默認(rèn)的值從父類怎么辦者疤?
可以寫一個(gè)module來實(shí)現(xiàn),代碼如下:
module ClassLevelInheritableAttributes
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def inheritable_attributes(*args)
@inheritable_attributes ||= [:inheritable_attributes]
@inheritable_attributes += args
args.each do |arg|
self.singleton_class.instance_eval do
attr_accessor :"#{arg}"
end
# class_eval %(
# class << self; attr_accessor :#{arg} end
# )
end
@inheritable_attributes
end
def inherited(subclass)
@inheritable_attributes.each do |inheritable_attribute|
instance_var = "@#{inheritable_attribute}"
subclass.instance_variable_set(instance_var, instance_variable_get(instance_var))
end
end
end
end
那么就可以實(shí)現(xiàn)了繼承相關(guān)的功能骇钦。
class P3
include ClassLevelInheritableAttributes
inheritable_attributes :sides
@sides = 1
end
P3.sides #=> 1
class O < P3; end
O.sides #=> 1
參考了《metaprogramming ruby》和這篇文章