这是我拥有的 Ruby 类:
class MyBase
class << self
def static_method1
@@method1_var ||= "I'm a base static method1"
end
def static_method1=(value)
@@method1_var = value
end
def static_method2
@@method2_var ||= "I'm a base static method2"
end
def static_method2=(value)
@@method2_var = value
end
end
def method3
MyBase::static_method1
end
end
class MyChild1 < MyBase
end
class MyChild2 < MyBase
class << self
def static_method1
@@method1_var ||= "I'm a child static method1"
end
end
end
c1 = MyChild1.new
puts c1.method3 #"I'm a base static method1" - correct
c2 = MyChild2.new
puts c2.method3 # "I'm a base static method1" - incorrect. I want to get "I'm a child static method1"
我知道attr_accessor
和模块,但我不能在这里使用它们,因为我希望它们在MyBase class
. 我想覆盖MyBase.static_method1
.MyChild2