[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Subclasses and constants

List Recv

3/27/2006 6:39:00 AM

Often, I find myself doing:

class RemoteCommand
def submit
sendto(URL, ...)
end
end

class GetStockPriceCommand
URL = 'http://...'
end

Which won't work.
I'm forced to do:

sendto(self.class::URL, ...)

which just seems akward. Same for using @@class_variables.

Why? More importantly, is there a better workaround?

5 Answers

Jim Weirich

3/27/2006 12:07:00 PM

0

List Recv wrote:
> Often, I find myself doing:
>
> class RemoteCommand
> def submit
> sendto(URL, ...)
> end
> end
>
> class GetStockPriceCommand
> URL = 'http://...'
> end
>
> Which won't work.
> I'm forced to do:
>
> sendto(self.class::URL, ...)
>
> which just seems akward. Same for using @@class_variables.
>
> Why? More importantly, is there a better workaround?

I assume you meant: class GetStockPriceCommand < RemoteCommand

If so then the following will work:


class RemoteCommand
def submit
sendto(url, ...)
end
def url
self.class::URL
end
end

class GetStockPriceCommand < RemoteCommand
URL = 'http://...'
end

--
-- Jim Weirich

--
Posted via http://www.ruby-....


List Recv

3/27/2006 3:25:00 PM

0

Jim,

Right, that's exactly what I meant, and that's in fact the work around
which I've been using.

My question is really why I need to do this, and if there is a better
way... It forces me to decide whether I'll ever subclass when I code
the parent, which seems unrubyish... I'd rather just code the parent,
and if the child changes the URL, so be it!

Robert Dober

3/27/2006 4:11:00 PM

0

On 3/27/06, listrecv@gmail.com <listrecv@gmail.com> wrote:
>
>
> the parent, which seems unrubyish... I'd rather just code the parent,
> and if the child changes the URL, so be it!



and that is exactly why you should not use a Constant.
Constants do not change, do they ;)?
You should use an instance variable and define accessor methods to it. (or
class variable for that matter)
These accessor methods are then used by the superclass.
This is a classic pattern, but I do not know its name in English, sorry.

Hope this helps
Robert




--
Deux choses sont infinies : l'univers et la bêtise humaine ; en ce qui
concerne l'univers, je n'en ai pas acquis la certitude absolue.

- Albert Einstein

List Recv

3/28/2006 3:19:00 AM

0

@@class_variables seemed to have the same behavior - if they were
changed in the subclass, and the parent defined a method, it wouldn't
have access to the subclass's definition.

(BTW - of course Constants don't change - but different subclasses
could have different ones - with them never changing - but I digress)

Robert Dober

3/28/2006 8:35:00 AM

0