accessing class constants in included modules

M

Martin DeMello

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
 
T

Tom Agnew

Martin said:
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
 
M

Martin DeMello

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
 
J

Joel VanderWerf

Martin said:
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!
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top