Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class is required but cannot be accessed

I have a very odd error I cannot wrap my head around.

Basically, I have this class in my lib folder:

# lib/api/amazon.rb
module API
  class Amazon
    ...
  end
end

When I want to use it somewhere, I require it:

require 'api/amazon'
API::Amazon.do_stuff

This works initially but after a while it breaks and raises NameError: uninitialized constant API::Amazon. When I debug this and try to require the file again when the error is raised, it returns false, indicating that the file was already loaded. I can also see it in $" (this list of loaded files). Why can I then not access API::Amazon?

Note: I added "API" as an acronym to ActiveSupport::Inflector which is why I don't have to use "Api":

# config/initializers/inflections.rb
ActiveSupport::Inflector.inflections do |inflect|
  inflect.acronym 'API'
end

EDIT:

I tried ::API::Amazon.do_stuff as well, same result.

like image 270
Manuel Meurer Avatar asked Nov 11 '22 17:11

Manuel Meurer


1 Answers

I write some code aimed to get same result as yours, maybe it can give some clue.

trytemp.rb:

module API
  class Amazon
    def hello
      puts "API::Amazon initially works well"
      $stdout.flush
    end
  end
end

s = API::Amazon.new
s.hello

p API.constants
API = Module.new
p API.constants # Here you can see constant Amazon disappers from module API
s = API::Amazon.new
s.hello

It initially works well, then get same error,"uninitialized constant API::Amazon (NameError)":

$ ruby trytemp.rb
API::Amazon initially works well
[:Amazon]
trytemp.rb:15: warning: already initialized constant API
[]
trytemp.rb:19:in `<main>': uninitialized constant API::Amazon (NameError)
like image 135
uncutstone Avatar answered Nov 14 '22 23:11

uncutstone