Rails lib包括

ste*_*ard 7 ruby-on-rails include

关于lib目录中定义的模块,我有一个令人费解的问题

我有两个文件

#lib/authentication.rb

module Authentication

end


#lib/test_module.rb

module TestModule

end
Run Code Online (Sandbox Code Playgroud)

在我的应用程序控制器中我有

 class ApplicationController < ActionController::Base
     include Authentication
     include TestModule
 end
Run Code Online (Sandbox Code Playgroud)

身份验证模块正确加载但TestModule没有

我得到"未初始化的常量ApplicationController :: TestModule"

我很难过......有人吗?

编辑:有谁知道我可以在哪里调试这个?

use*_*833 21

从Rails 3开始,确保将lib目录添加到config.autoload_pathsin中config/application.rb,以便读取包含模块的文件并加载模块.

config.autoload_paths += %W(#{config.root}/lib)
Run Code Online (Sandbox Code Playgroud)

看看这里对这个和装载子目录更多信息.

另外,据说 " 你不应该在rails应用程序中使用require,因为它可以防止[un]正确加载该代码的ActiveSupport :: Dependencies".


Veg*_*ger 5

require 'lib/test_module'在ApplicationController文件的顶部添加可能会有所帮助

  • 试过那个,这就是我没有加载这样的文件 - lib/test_module(MissingSourceFile) (2认同)
  • 你确定文件在正确的位置?由于require语句无法找到它... (2认同)