Steve B.
Steve B.

Reputation: 57284

Get a reference to the enclosing module in ruby

How do you get a reference to the enclosing module in ruby?

module Foo
   @@variable=1

   def variable
      @@variable
   end

    class A
      def somemethod
         puts "variable=#{Foo.variable}" #<--this won't run, resolving Foo 
                                        # as the class instead of the module
      end
    end

    class Foo
        ... # doesn't matter what's here
    end
end

I ran into this question caused by naming confusion. While the names are easy enough to fix, I"m wondering what the "correct" way is to do this in ruby. If I try to run this it seems like ruby is trying to resolve Foo.variable as Foo::Foo.variable which of course fails. It seems like there should be a simple way in the language to refer to the outer module method.

Upvotes: 3

Views: 1014

Answers (1)

oesgalha
oesgalha

Reputation: 178

You can get the outer module reference by adding the :: prefix to Foo:

::Foo.variable

In your example code:

module Foo
   @@variable=1

   def variable
      @@variable
   end

    class A
      def somemethod
         puts "variable=#{::Foo.variable}"
      end
    end

    class Foo
        ... # doesn't matter what's here
    end
end

Upvotes: 3

Related Questions