Search code examples
ruby-on-railsrubyrspecrspec-railsactivesupport

Namespaced class on rails' app folder


I have the following folder structure:

app
├── assets
├── controllers
├── helpers
├── mailers
├── market_adapters
│   └── german.rb
│...

And the file market_adapters/german.rb is:

module MarketAdapters #(I've also tried naming it singular)
   class German
   end
end

When running tests I get the error:

/gems/activesupport-5.0.0/lib/active_support/dependencies.rb:512:in
`load_missing_constant': Unable to autoload constant German, 
expected .../app/market_adapters/german.rb to define it (LoadError)

Adding the market_adapters folder to the autoload_paths seems to have no effect config.autoload_paths << "#{Rails.root}/app/market_adapters"

If I move the market_adapters to the lib folder, everything works. But still would like to have it under app, any ideas?

By the way, I'm using Rails 5.


Solution

  • All the subfolders in app are automatically auto-loaded and added to the load path. Therefore, the folder market_adapters is added to the load path, and the file called german.rb is expected to define the German class.

    If you really want to use market_adapters as namespace and keep the file in app, you need to store it in the folder app/market_adapters/market_adapters/german.rb.

    The right place, however, is in lib.