更新时间:2022-11-04 21:15:28
今天我自己也碰上了这个,决定下潜.
Just ran into this myself today and decided to dive deep.
在ActiveSupport::Dependencies.autoload_paths
中看不到要添加到config/application.rb
中的config.autoload_paths
中的路径的原因是,在初始化应用程序之前,它们不会被复制.请参见railties
宝石中的rails/engine.rb
:
The reason you don't see in ActiveSupport::Dependencies.autoload_paths
the paths you're adding to config.autoload_paths
in config/application.rb
is that they aren't copied over until the application is initialized. See rails/engine.rb
in the railties
gem:
module Rails
class Engine < Railtie
…
# Set the paths from which Rails will automatically load source files,
# and the load_once paths.
#
# This needs to be an initializer, since it needs to run once
# per engine and get the engine as a block parameter
initializer :set_autoload_paths, :before => :bootstrap_hook do |app|
ActiveSupport::Dependencies.autoload_paths.unshift(*_all_autoload_paths)
ActiveSupport::Dependencies.autoload_once_paths.unshift(*_all_autoload_once_paths)
# Freeze so future modifications will fail rather than do nothing mysteriously
config.autoload_paths.freeze
config.eager_load_paths.freeze
config.autoload_once_paths.freeze
end
…
def _all_autoload_paths
@_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq
end
…
end
end
您是不是偶然地尝试从config/application.rb
内部甚至更早地从需要config/application.rb
的脚本或模块中调用MyClass
?如果是这样,您将必须明确要求定义MyClass
的文件,例如:
Were you by any chance trying to invoke MyClass
from within config/application.rb
or, even earlier, from a script or module that requires config/application.rb
? If so, you'll have to explicitly require the file defining MyClass
, e.g.:
require File.expand_path('../../somefolder/my_class', __FILE__)
# now use MyClass