Tom Rossi
Tom Rossi

Reputation: 12066

Understanding "LoadError: Unable to autoload constant"

I see this question has been asked a bunch of times, but none of the solutions seem to be working.

I intermittently get this issue:

LoadError: Unable to autoload constant Directory::Apple::Listing, expected /my/path/lib/directory/apple/listing.rb

But the "expected" file is exactly the file that defines the constant?

## /my/path/lib/directory/apple/listing.rb

module Directory
  class Apple::Listing
    ...
  end
end

The lib folder is included in the autoload_paths:

# application.rb

config.autoload_paths += %W(#{config.root}/lib)

If I do a spring stop it will work for a while, but then I will inevitably see that annoying error again. What am I missing?

Upvotes: 2

Views: 1695

Answers (1)

max
max

Reputation: 101811

Define (and reopen) namespaced classes and modules using explicit nesting. Using the scope resolution operator can lead to surprising constant lookups due to Ruby’s lexical scoping, which depends on the module nesting at the point of definition.
- The Ruby Style Guide

# /lib/directory/apple/listing.rb
module Directory
  class Apple
    class Listing
    end
  end
end

Upvotes: 1

Related Questions