xeroshogun
xeroshogun

Reputation: 1092

Module automatically adding namespace to a method being called

I'm trying to create a gem, my gem requires a different gem that I have added into the gemspec.

My issue is when I try to call a method inside the code, ruby automatically adds the module namespace to the method I am calling, then I get an uninitialized constant error. I put a basic example of what is going on below.

lib/example_gem.rb

module FooModule

  def bar
    # this is the method I am trying to run
    BAZ::Request.execute(123)
  end
end

class Test
  include FooModule    
end

x = Test.new
x.bar

=>>>>>>>> uninitialized constant FooModule::Baz (NameError)

I'm not trying to call FooModule::Baz, I want to call BAZ::Request.execute(123). Any help would be appreciated

Upvotes: 2

Views: 265

Answers (1)

guitarman
guitarman

Reputation: 3320

Try:

::BAZ::Request.execute(123)

The keyword is "constant lookup operator". I assume BAZ isn't wrapped into another class or module, so you need to look for it on the topmost level. Therefore you prepend ::.

And now you understand why the request (BAZ::Request) needs to be within BAZ.

Upvotes: 3

Related Questions