[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Class attribute unique to subclasses but used in parent class

lcor1979@gmail.com

10/28/2006 1:32:00 PM

Hello,

I'm new in the Ruby World and I have a question.

Let's say I have a class with a class attribute (I call this class
Parent), this class attribute is used in instance methods of Parent.
Parent class has many subsclasses. Each subsclass should have it's own
value of the class attribute.

Example:

class Parent
@@test = nil

def Parent.create(value)
@@test=value
new
end

def print_test
puts @@test
end
end

class Child1 < Parent
end

class Child2 < Parent
end

c1 = Parent.create '1'
c1.print_test # => 1
c2 = Parent.create '2'
c2.print_test # => 2
c1.print_test # => 2


What I'll like, is that Child1 and Child2 have their own values of
@@test, but @@test should be initialized and used in Parent.
Also, @@test cannot be an instance variable because it is heavy to
initialize and will be common to all instances of Child1 or Child2.

Thank you

3 Answers

dblack

10/28/2006 1:44:00 PM

0

David Vallner

10/28/2006 4:10:00 PM

0

lcor1979@gmail.com wrote:
> What I'll like, is that Child1 and Child2 have their own values of
> @@test, but @@test should be initialized and used in Parent.
> Also, @@test cannot be an instance variable because it is heavy to
> initialize and will be common to all instances of Child1 or Child2.
>

Class variables and class instance variables sound way too much like
global state coming into the system through a backdoor, I'd avoid both.

Personally, I'd replace lookup through a class variable or class
instance variable with injecting the shared object into instances. The
less shared state, the more flexibility you gain in being able to rewire
your objects.

Disclaimer: I am biased in favour of IoC and DI based "objects floating
in vacuum" designs, especially for scenarios that involve reusing an
expensive-to-create component like this one. If nothing else,
declarative dependency resolution lets you plug in testing components
easier / clearer than imperative (even if Ruby makes the latter easier
in that you're allowed to molest any object in arbitrary ways.)

David Vallner

dblack

10/28/2006 4:17:00 PM

0