attr_reader, etc for class variables

D

Daniel Finnie

Is there such a thing?

If I have the following code:
class Klass
@@var = 0
end

How can I make an attr_writer for it besides doing
class Klass
def var=(other)
@@var = other
end
end

I've tried all of these to no avail:
attr_writer :'Klass.var' # => `attr_writer': invalid attribute name
`Klass.var' (NameError)

attr_writer :'var' # => undefined method `currentRound=' for Team:Class
(NoMethodError) (when I try to use the writer function later)

attr_writer :'self.class.var' # => `attr_writer': invalid attribute name
`self.class.var' (NameError)


Any ideas? I mean it's not a huge deal but I would like to find a way
around making the method described above.

Thanks,
Dan
 
E

Eric Hodel

Is there such a thing?
No.

If I have the following code:
class Klass
@@var = 0
end

How can I make an attr_writer for it besides doing
class Klass
def var=(other)
@@var = other
end
end

I tend to use instance variables for this as class variables usually
give me hard-to-find bugs.

class Klass
@var = 0

class << self
attr_accessor :var
end

def some_method
self.class.var
end
end

p Klass.var # => 0
p Klass.new.some_method # => 0
 
D

Devin Mullins

Daniel said:
Is there such a thing?
Rails' ActiveSupport provides them as cattr_* and mattr_*. For that
matter, they're not that hard to write. For that matter, what Eric said.

Devin
What, me matter?
 
D

dblack

Hi --

Rails' ActiveSupport provides them as cattr_* and mattr_*. For that matter,
they're not that hard to write. For that matter, what Eric said.

I'd add that if you write them (and I agree with Eric that instance
variables are much better for this; indeed, something is pretty much
always better than class variables for everything), it's best to name
them something else. "attr" names suggest an attribute of an object,
but since class variables are not uniquely associated with any one
object, they're not a good fit for recording an attribute.


David

--
David A. Black | (e-mail address removed)
Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top