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

会有一股神秘感。 提交于 2019-12-03 09:18:02

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.

In my case spring was not watching the app/services directory for changes - restarting Spring would load the class but changes to an existing class or new class would require a restart of Spring for them to apply.

To resolve this issue I added it to the list of directories watched by Spring in config/spring.rb:

%w(
  .ruby-version
  .rbenv-vars
  tmp/restart.txt
  tmp/caching-dev.txt
  app/services
).each { |path| Spring.watch(path) }

and restarted Spring one more time.

I came with a similar problem, and took a quick glance at the Spring docs and found this bit about watchers.

I added the following to my application.rb and things fell into place -

Spring.watch "app/services/**"

I'm no expert here, ymmv.

I was having the same problem, and found no solution. I'm not patient enough to wait for autoload to load it eventually, so my quick solution was to turn eager_load on, and start my server. It will finally load it. I switched it off afterwards and my classes were still loaded.

Just use: config.eager_load = true

in your config/environments/development.rb

You should include it into autoload_paths:

config.autoload_paths += %W(#{Rails.root}/app/services)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!