Why doesn't Rails autoload classes from app/services?

linkyndy picture linkyndy · Sep 30, 2015 · Viewed 27k times · Source

I'm working on a Rails 4.2 app and have just added app/services/fetch_artists.rb to the structure. Inside this file, I have defined a class FetchArtists; end.

When trying to run rails r 'FetchArtists' it gives me a NameError: uninitialized constant FetchArtists.

I've tried looking at ActiveSupport::Dependencies.autoload_paths and indeed, app/services is not there:

/.../app/assets
/.../app/controllers
/.../app/helpers
/.../app/jobs
/.../app/mailers
/.../app/models
/.../app/controllers/concerns
/.../app/models/concerns
/.../spec/mailers/previews

My question is, why isn't this folder automatically loaded, and what should I do for it to be?

EDIT

Very strange, after repeatedly running the above command with rails runner, the new folder appears on the autoload paths. I have no idea why this happened with such a lag.

Someone suggested this may deal with spring. I would like to hear more on this, since it can possibly help many others in this situation too.

Answer

maknz picture maknz · Dec 29, 2016

I encountered the same problem and it seems to be a caching issue with Spring, a process which handles preloading your app. It's used for the web server as well as the console and Rake tasks.

Stopping Spring with bin/spring stop will force Spring to load your app fresh. Now running rails console and inspecting ActiveSupport::Dependencies.autoload_paths will successfully show app/services.