为什么 Rails 不从应用程序/服务自动加载类? [英] Why doesn't Rails autoload classes from app/services?

查看:26
本文介绍了为什么 Rails 不从应用程序/服务自动加载类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Rails 4.2 应用程序,并且刚刚将 app/services/fetch_artists.rb 添加到结构中.在这个文件中,我定义了一个 class FetchArtists;结束.

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.

当尝试运行 rails r 'FetchArtists' 时,它给了我一个 NameError: uninitialized constant FetchArtists.

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

我试过查看 ActiveSupport::Dependencies.autoload_paths 并且确实,app/services 不存在:

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?

编辑

很奇怪,在用rails runner重复运行上述命令后,新文件夹出现在自动加载路径上.我不知道为什么会发生这样的滞后.

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.

有人建议这可能与spring有关.我想听到更多关于这方面的信息,因为它也可能在这种情况下帮助许多其他人.

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.

推荐答案

我遇到了同样的问题,这似乎是 Spring 的缓存问题,Spring 是一个处理预加载应用程序的进程.它用于 Web 服务器以及控制台和 Rake 任务.

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.

使用 bin/spring stop 停止 Spring 将强制 Spring 重新加载您的应用程序.现在运行 rails 控制台 并检查 ActiveSupport::Dependencies.autoload_paths 将成功显示 app/services.

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.

这篇关于为什么 Rails 不从应用程序/服务自动加载类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆