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
CodePudding user response:
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