[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

accessing class constants in included modules

Martin DeMello

11/8/2006 7:17:00 AM

module Foo
def display
puts self.class::A
end
end

class Bar
A = 5
include Foo
end

class Baz
A = 6
include Foo
end

Bar.new.display
Baz.new.display


Anything cleaner-looking than self.class::Constant to access the
constant from a method defined in the module?

martin

3 Answers

Tom Agnew

11/9/2006 5:36:00 AM

0

Martin DeMello wrote:
> module Foo
> def display
> puts self.class::A
> end
> end
>
> class Bar
> A = 5
> include Foo
> end
>
> class Baz
> A = 6
> include Foo
> end
>
> Bar.new.display
> Baz.new.display
>
>
> Anything cleaner-looking than self.class::Constant to access the
> constant from a method defined in the module?
>
> martin
>

Here's a trick I use to beautify access to constants:

class Object
def my
self.class
end
end

.....Now all constants can be accessed with my::Constant.

I find it more readable. Certainly less typing!

Cheers,
Tom Agnew

Martin DeMello

11/9/2006 10:16:00 AM

0

On 11/9/06, Tom Agnew <agnewtj@nospam.net> wrote:

> Here's a trick I use to beautify access to constants:
>
> class Object
> def my
> self.class
> end
> end
>
> ....Now all constants can be accessed with my::Constant.
>
> I find it more readable. Certainly less typing!

Ah - nice!

martin

Joel VanderWerf

11/9/2006 7:56:00 PM

0

Martin DeMello wrote:
> On 11/9/06, Tom Agnew <agnewtj@nospam.net> wrote:
>
>> Here's a trick I use to beautify access to constants:
>>
>> class Object
>> def my
>> self.class
>> end
>> end
>>
>> ....Now all constants can be accessed with my::Constant.
>>
>> I find it more readable. Certainly less typing!
>
> Ah - nice!

This may be a corner case, but if you're going to define #my at the
instance level, it should probably be based on the
(singleton|eigen)class of the instance and not the "birth" class:

class Object
def my
self.class
#class << self; self; end
end
end

class Foo
C = 2
end

x = Foo.new
class << x
X = 3
end

p x.my::C
p x.my::X

Now try it with the alternative!

--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407