Rails lib includes

2020-03-18 04:03发布

问题:

I have a puzzling issue regarding modules defined in the lib dir

I have two files

#lib/authentication.rb

module Authentication

end


#lib/test_module.rb

module TestModule

end

In my application controller I have

 class ApplicationController < ActionController::Base
     include Authentication
     include TestModule
 end

The Authentication Module loads properly but the TestModule does not

I get "uninitialized constant ApplicationController::TestModule"

I am stumped... anyone?

EDIT: Does anyone know where I could look to debug this?

回答1:

Adding require 'lib/test_module' at the top of your ApplicationController file might help



回答2:

As of Rails 3, make sure to add the lib directory to config.autoload_paths in config/application.rb, so that the file containing your module is read and the module is loaded.

config.autoload_paths += %W(#{config.root}/lib)

Look here for more info on this and loading subdirectories.

Also, supposedly "you shouldn't use require within a rails app, because it prevents ActiveSupport::Dependencies from [un]loading that code properly".