Constant visibility

N

Nicholas Wieland

Hi *,

module Included

def whatever
do_something_with FOO
end

end

module Includer

include Included

class Whatever
FOO = 'whatever'
end

end

this is not just an example to invent stupid variable names, but a
question.
I would like to include the Included module and have visibility on the
Includer module constants (think about validation, different classes
need different data).
Can you suggest me a way to accomplish that, to have a method inside a
module that checks data inside a class in another module, and define
the rules in the class itself ?
"You're an idiot you should do like that" answers are welcome :)

ngw
 
S

Sean O'Halpin


[snip example code]
Can you suggest me a way to accomplish that, to have a method inside a
module that checks data inside a class in another module, and define the
rules in the class itself ?

This is one approach:

module Included
def whatever
puts self.class::FOO
end
end

module Includer
class Whatever
include Included
FOO = 'whatever'
end
end

o = Includer::Whatever.new
o.whatever # => "whatever"

Note you have to include the module inside the class - including it in
the enclosing module does not do what you may think :)

Regards,
Sean
 
B

Bernardo Monteiro Rufino

[Note: parts of this message were removed to make it a legal post.]

You might be looking for extend instead of include:
module Foo
def foo
puts self::FooBar::TEST;
end


module Bar
extend Foo;
class FooBar
TEST = "Whatever";
end


Bar.foo; # Prints out "Whatever"

See if it works for you


[snip example code]
Can you suggest me a way to accomplish that, to have a method inside a
module that checks data inside a class in another module, and define the
rules in the class itself ?

This is one approach:

module Included
def whatever
puts self.class::FOO
end
end

module Includer
class Whatever
include Included
FOO = 'whatever'
end
end

o = Includer::Whatever.new
o.whatever # => "whatever"

Note you have to include the module inside the class - including it in
the enclosing module does not do what you may think :)

Regards,
Sean
 

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

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,705
Latest member
Stefkari24

Latest Threads

Top