need for a class_attr methods collection

L

Lionel Thiry

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
 
T

ts

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)
 
L

Lionel Thiry

ts said:
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
 

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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top