问题描述
我将文件名 g.rb 放在 Rails.root/lib
文件夹中文件内容是这样的:
I place a file name g.rb in side Rails.root/lib
folderThe file content is like this:
module Google
end
然后我添加
config.autoload_paths += %W(#{config.root}/lib #{Rails.root}/app/delayed_jobs)
到我的Rails.root/config/application.rb
但是,当我尝试从 rails 控制台
调用 Google 时,会引发异常.只有当我执行 require 'google'
时,异常才会消失.为什么?我的文件不应该自动加载吗,我不应该在没有任何额外的 require
语句的情况下访问模块吗?
However, when I try to invoke Google from rails console
, an exception is thrown. The exception goes away only if I execute require 'google'
. Why? Shouldn't my file is autoloaded and shouldn't I access the module without any extra require
statement?
推荐答案
嗯,我发现了一件有趣的事情.为了让 Rails 自动加载我的类,类名应该符合文件名和文件夹结构.例如,如果我想自动加载 Google 模块,我必须将它放在 google.rb
中,直接放在/lib 下(如果我指定从/lib 自动加载).如果我想自动加载 Google::Docs
,那么我要么把它放在 google.rb
或 google/docs.rb
Hmm, I discovered an interesting thing. In order for Rails to auto load my class, the class name should be compliant to the file name and the folder structure.For example, if I want to have Google module autoloaded, I must placed it inside google.rb
, directly under /lib (incase I specify autoload from /lib).If I want to auto load Google::Docs
, then I either place it inside google.rb
or google/docs.rb
这篇关于将 lib 添加到 Rails 3 中的“config.autoload_paths"不会自动加载我的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!