Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LoadError Unable to autoload constant

It seems that autoloader is loading up lib/tools/address and not my model

Address throws the following error

LoadError: Unable to autoload constant Address, expected /lib/tools/address.rb to define it

Can someone tell me what I'm doing wrong. I thought that
Address would point to constant models/address.rb
and
Tools::Address to lib/tools/address.rb

app/models/address.rb

class Address
  blah
end

lib/tools/address.rb

module Tools
  class Address
    blah blah
  end
end
like image 729
bopritchard Avatar asked Feb 07 '23 00:02

bopritchard


1 Answers

In my experience it can be tricky to use multiple constants with the same name but with different namespaces. In your case you have two Address constants, one at the top level and another inside the Tools namespace. This can confuse the Rails autoloader.

Some possible solutions:

When you want to use the top-level Address (i.e. your model), refer to it explicitly using ::Address.

If that doesn't work, you can also use require_dependency to give the autoloader a hint of what you want. At the top of the file that is giving you the LoadError, put this line:

require_dependency("address")

Here's the documentation:

require_dependency

Interprets a file using mechanism and marks its defined constants as autoloaded. file_name can be either a string or respond to to_path.

Use this method in code that absolutely needs a certain constant to be defined at that point. A typical use case is to make constant name resolution deterministic for constants with the same relative name in different namespaces whose evaluation would depend on load order otherwise.

like image 167
Matt Brictson Avatar answered Feb 08 '23 23:02

Matt Brictson