Forum: Ruby Constant visibility

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Bd0ecd69dba2aab1a0261ee46e090139?d=identicon&s=25 Nicholas Wieland (Guest)
on 2008-12-31 00:22
(Received via mailing list)
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
E1d641bfe4071a5413bac781f06d3fd1?d=identicon&s=25 Sean O'halpin (sean)
on 2008-12-31 01:31
(Received via mailing list)
On Tue, Dec 30, 2008 at 11:20 PM, Nicholas Wieland
<nicholas.wieland@gmail.com> wrote:
> Hi *,

[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
606384686bc1be42acd5a1f610613e66?d=identicon&s=25 Bernardo Rufino (bermonruf)
on 2009-01-01 08:22
(Received via mailing list)
You might be looking for extend instead of include:

> module Foo
>

>
  def foo
>
    puts self::FooBar::TEST;
>
  end
>

>
end
>

> module Bar
>

>
  extend Foo;
>

>
  class FooBar
>
    TEST = "Whatever";
>
  end
>

> end
>

> Bar.foo;  # Prints out "Whatever"
>

See if it works for you
This topic is locked and can not be replied to.