Jacob Dalton
Jacob Dalton

Reputation: 1693

Rails Autoloading Nested Class: LoadError (Unable to autoload constant ModuleName::ClassName)

I use app/services to organize a collections of service classes. For example I have a light wrapper around NewRelic transactions listed in app/services/metrics/transaction.rb.

Rails autoloading has a tough time with this for some reason. I'll get constant loading errors like:

LoadError (Unable to autoload constant Metrics::Transaction, expected /Users/home/company/repo-name/app/services/metrics/transaction.rb to define it)

Of course the file (and 3 siblings to it) are defined in the listed location. This isn't an issue in production environments in which the constants are eager loaded.

The path is under app and I've checked the autoload paths so the file should be loaded, yet I have this problem whenever the constant gets hit for the first time.

Upvotes: 2

Views: 1016

Answers (1)

Jacob Dalton
Jacob Dalton

Reputation: 1693

The key here seems to be that the constant is nested. It appears that the constant loader first attempts to load the module Metrics and failing to find that, issues an error.

If you create a file in app/services (or whatever your corresponding app/* autoloaded directory is) that defines the module constant:

# app/services/metrics.rb
module Metrics
end

then the autoloader will be able to cleanly load classes defined in app/services/metrics/*.

Upvotes: 3

Related Questions