0

Suppose I have a Bar module in the most out scope like this:

module Bar
  def hello
    puts('hello')
  end
end

and I also have another Bar module defined inside a Foo module like this:

module Foo
  module Bar
   def self.run
     Bar::hello
   end
  end
end

How can I include the hello method defined in the most outern Bar module to be used inside the Bar module defined inside the Foo module?

When trying to do this I'm getting:

NameError: uninitialized constant Foo::Bar::hello

1 Answer 1

2

You can extend top level module Bar and use :: constant prefix to start looking in the global namespace:

module Bar
  def hello
    puts('hello from top level Bar')
  end
end

module Foo
  module Bar
    extend ::Bar

    def self.run
      hello
    end
  end
end

Foo::Bar.run # >> hello from top level Bar

Or without extend:

module Bar
  def self.hello
    puts('hello from top level Bar')
  end
end

module Foo
  module Bar

    def self.run
      ::Bar.hello
    end
  end
end

Foo::Bar.run # >> hello from top level Bar
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the two alternatives and for explaining about the :: constant prefix. Worked like charm!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.