Class variables are never required. But the reason is not that they are separated. I mean, it's good to avoid a shared state where you can, but this is not a real problem.
The reason they are recommended is, as shown in this article, they are really confusing . In particular, class variables of a class are separated by its subclasses and instances of its subclasses. For example:
class Parent end class Child1 < Parent @@class_var = "Child1's" end class Child2 < Parent @@class_var = "Child2's" end
With this code, Child1 and its instances will see a class variable named @@class_var with the value "Child1's" and Child2, and all its instances will see the class variable named @@class_var with the value "Child2's" . But suppose we later open Parent again and write the following:
class Parent @@class_var = "Parent's" end
Now, Parent and the instances it creates will see a class variable named @@class_var with the value "Parent's" . But that is not all . Now that the parent class has this variable, Child1 and Child2 suddenly share this variable, so all @@class_var have the value "Parent's" . And if you reassign the variable to Child1, it still shares, so all classes are updated. How confusing!
Instead of class variables, you can simply use class instance variables, for example:
class Parent @class_var = "Parent's" def self.class_var @class_var end end class Child1 < Parent @class_var = "Child1's" end class Child2 < Parent @class_var = "Child2's" end
Now Parent.class_var will return “Parent's”, Child1.class_var will return “Child1's” and Child2.class_var will return “Child2's” - exactly as you expect.
Chuck May 16 '12 at 8:02 2012-05-16 08:02
source share