[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

need for a class_attr methods collection

Lionel Thiry

3/12/2005 2:08:00 PM

Hello,
I believe there is a need in class_attr methods collection.

We all know the attr collection:
attr_reader :my_var
attr_writer :my_other_var
attr_accessor :my_best_var

They create those methods:
def my_var
@my_var
end

def my_other_var=(value)
@my_other_var = value
end

But there are also class variables:

class MyClass
@a = "value"

def self.a
@a
end
end
puts Test.a # it works

It would be easier to write it this way:

class MyClass
@a = "value"

class_attr_reader :a
end
puts Test.a # it doesn't work

I know class variables are already accessible through @@a. But it violates some
OO principles: as the class itself is an object, it allows another object (its
instances) to access its internals. Ruby forbid this for normal objects, why
then allowing this for class objects?

It may have changed, but I believe '@@' will disapear in ruby2 because of that
violation. That's why I try myself to get used in avoiding the use of '@@'. And
that's why I've realised the need for class_attr methods collection.

Any opinions?

Regards,
Lionel Thiry
2 Answers

ts

3/12/2005 2:13:00 PM

0

>>>>> "L" == Lionel Thiry <lthiryidontwantspam@skynetnospam.be> writes:
L> class MyClass
L> @a = "value"

L> class_attr_reader :a

class << self
attr_reader :a
end

L> end
L> puts Test.a # it doesn't work

L> I know class variables are already accessible through @@a.

No, don't make confusion between class instance variable (i.e. @a in your
example) and class variables (i.e. @@a)

--

Guy Decoux

Lionel Thiry

3/12/2005 2:36:00 PM

0

ts wrote:
>>>>>>"L" == Lionel Thiry <lthiryidontwantspam@skynetnospam.be> writes:
>
> L> class MyClass
> L> @a = "value"
>
> L> class_attr_reader :a
>
> class << self
> attr_reader :a
> end
>
> L> end
> L> puts Test.a # it doesn't work
Oh my! Completly forgotten that way of writing things. Thnaks for the tip.

>
> L> I know class variables are already accessible through @@a.
>
> No, don't make confusion between class instance variable (i.e. @a in your
> example) and class variables (i.e. @@a)
>
Really?
*making some test*
You're right, indeed. Sorry for the confusion.

Regards,
Lionel Thiry