[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

equivalent of attr_accessor for class variables?

bwv549

7/13/2006 8:52:00 PM

It is simple to set a class constant in ruby:

class Foo
CLASS_CONSTANT = "never to change"
end

And accessed like this:
Foo::CLASS_CONSTANT

However, I'd like to be able to create a class variable that is easily
accessible (read/write) by outside users without having to write class
accessor methods. How can I do this?

A really ugly way to set the variable without an accessor would be
this:
class Foo; @@class_constant = "newvalue" end
but that is write only.

The syntax:
Foo.class_constant = "newvalue"
would be preferable, but how to do this without writing accessor
methods?

Thanks

9 Answers

Ara.T.Howard

7/13/2006 9:02:00 PM

0

bwv549

7/13/2006 9:12:00 PM

0

> class C
> class << self
> attr_accessor 'class_constant'
> end
> end

For an intermediate ruby user, could you explain what is happening in
the line: 'class << self'

Thanks

dblack

7/13/2006 9:15:00 PM

0

dblack

7/13/2006 9:19:00 PM

0

Ara.T.Howard

7/13/2006 9:22:00 PM

0

dblack

7/13/2006 9:23:00 PM

0

Ara.T.Howard

7/13/2006 9:24:00 PM

0

Rob Sanheim

7/13/2006 11:12:00 PM

0

On 7/13/06, bwv549 <jtprince@gmail.com> wrote:
> It is simple to set a class constant in ruby:
>
> class Foo
> CLASS_CONSTANT = "never to change"
> end
>
> And accessed like this:
> Foo::CLASS_CONSTANT
>
> However, I'd like to be able to create a class variable that is easily
> accessible (read/write) by outside users without having to write class
> accessor methods. How can I do this?
>
> A really ugly way to set the variable without an accessor would be
> this:
> class Foo; @@class_constant = "newvalue" end
> but that is write only.
>
> The syntax:
> Foo.class_constant = "newvalue"
> would be preferable, but how to do this without writing accessor
> methods?
>
> Thanks

Here's the Rails implementation if you just want to see one working
implementation. Note that it allows you to access the class attribute
from the class and from instances (which is similiar to static members
in Java, actually).

http://dev.rubyonrails.org/svn/rails/trunk/activesupport/lib/active_support/core_ext/class/attribute_ac...

- Rob
--
http://www.robs...
http://www.seekin...
http://www.a...

Trans

7/14/2006 1:42:00 AM

0


ara.t.howard@noaa.gov wrote:

> class C
> class << self
> attr_accessor 'class_constant'
> end
> end

require 'facet/functor'

module Kernel

# Provides access to an object's metaclass (ie. singleton)
# by-passsing access provisions. So for example:
#
# class X
# meta.attr_accesser :a
# end
#
# X.a = 1
# X.a #=> 1

def meta
@_meta_functor ||= Functor.new do |op,*args|
(class << self; self; end).send(op,*args)
end
end

end

T.