Hi --
I know that attr_accessor works for accessing instance variables, but it
doesn't seem to work for class ones. What is the best way to set/retrieve the
value of a class variable?
@@var = 1
@@var
If you want to wrap them in methods:
class C
def C.var
@@var
end
def C.var=(x)
@@var = x
end
end
In Rails, there's a thing called "cattr" that does this automatically:
class C
cattr_acccessor :var
end
It's a little misleading, though. The term "attribute" (or attr)
refers to an attribute or property of an object. Class variables are
very promiscuous: they're shared among many objects (a class, its
descendants, all instances of all of those classes), so a class
variable is not really the right choice for an "attribute", and "attr"
is not the best name for wrappers around class variables.
If you want to represent state per class, the best way is to give your
class an instance variable or accessor:
class C
class << self # C's singleton class
attr_accessor :var
end
end
David
--
Upcoming training from Ruby Power and Light, LLC:
* Intro to Ruby on Rails, Edison, NJ, October 23-26
* Advancing with Rails, Edison, NJ, November 6-9
Both taught by David A. Black.
See
http://www.rubypal.com for more info!