Say I have a class with several “static” variables. I want a subclass of this class to be able to override these variables without affecting the original class. This is not possible using class variables, as they appear to be shared between subclasses and superclasses:
class Foo @@test = "a" def speak; puts @@test; end end class Bar < Foo @@test = "b" end Bar.new.speak
Cannot use constants:
class Foo TEST = "a" def speak; puts TEST; end end class Bar < Foo TEST = "b" end Bar.new.speak
Methods defined in the superclass ignore constants in the subclass.
An obvious workaround is to define methods for variables that must be "redefined":
class Foo def test; "a"; end end
But that sounds like a hack. I feel that this should be possible using class variables and that I'm probably just doing it wrong. For example, when I subclass Object (which happens by default):
class Foo < Object @@bar = 123 end Object.class_variable_get(:@@bar)
Why is @@bar not set to Object , as it was in my example Bar < Foo above?
To summarize: how to override a variable in a subclass without affecting the superclass?
Hubro source share