autoloading in Rails

using non-standard directories in Rails project (lib/, system/, etc.).

autoload_paths and eager_load_paths

  1. http://urbanautomaton.com/blog/2013/08/27/rails-autoloading-hell
  2. http://blog.arkency.com/2014/11/dont-forget-about-eager-load-when-extending-autoload

by default only subdirectories of app/ are added to autoload_paths and eager_load_paths (the latter is used in environments with eager loading - staging or production).

other directories (say, lib/) added manually to autoload_paths are not added to eager_load_paths automatically - it’s necessary to do it explicitly in config/application.rb:

config.autoload_paths += Dir["#{config.root}/lib/**/"]
config.eager_load_paths += Dir["#{config.root}/lib"]

the same in one go (note it’s not necessary to add all nested directories):

config.paths.add 'lib', eager_load: true

not adding them to eager_load_paths not only causes performance issues (classes inside lib/ are lazy loaded in production) but also might be the source of weird uninitialized constant errors.

to sum up always add non-standard directories to both autoload_paths and eager_load_paths to avoid loading errors in production.

using modules to namespace classes

2 ways to organize code in non-standard directories: