将目录添加到 Rails 中的加载路径? [英] Adding a directory to the load path in Rails?
问题描述
从 Rails 2.3 开始,将目录添加到加载路径以使其与 Rails 的自动重新加载机制挂钩的正确方法是什么?
As of Rails 2.3, what's the right way to add a directory to the load path so that it hooks into Rails' auto-reloading mechanisms?
我想到的具体例子是我有一个类有几个使用 STI 的子类,我认为将它们放在一个子目录中而不是将顶级弄乱是个好主意.所以我会有类似的东西:
The specific example I'm thinking of is I have a class that has several sub-classes using STI and I thought it would be a good idea to put them in a sub-directory rather than clutter the top-level. So I would have something like:
#app/models/widget.rb
class Widget < ActiveRecord::Base
add_to_load_path File.join(File.dirname(__FILE__), "widgets")
end
#app/models/widgets/bar_widget.rb
class BarWidget < Widget
end
#app/models/widgets/foo_widget.rb
class FooWidget < Widget
end
这是我正在寻找的 add_to_load_path
方法.
It's the add_to_load_path
method that I'm looking for.
推荐答案
在当前版本的 Rails (3.2.8) 中,这已在 application.rb 文件中进行了更改.
In the current version of Rails (3.2.8), this has been changed in the application.rb file.
当前代码注释为:
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
需要更新 autoload_paths 值.尝试修改之前的 load_paths 变量会导致此错误.
Will need to update the autoload_paths value. Attempting to modify the the former load_paths variable causes this error.
/configuration.rb:85:in `method_missing': undefined method `load_paths' for #<Rails::Application::Configuration:0xac670b4> (NoMethodError)
例如,对于要添加到 autoload_paths 配置的每个路径,添加类似于以下内容的行:
for an example, for each path to add to autoload_paths config, add a line similar to the following:
config.autoload_paths += %W(#{config.root}/app/validators)
<小时>
config.autoload_paths
接受一个路径数组,Rails 将从这些路径自动加载常量.默认为app
下的所有目录.
config.autoload_paths
accepts an array of paths from which Rails will autoload constants. Default is all directories under app
.
http://guides.rubyonrails.org/configuring.html
来自以下评论者(hakunin):
From commentor (hakunin) below:
如果目录在 app/
下,你不需要在任何地方添加它,它应该在默认情况下工作(肯定在 3.2.12 中).Rails 有 eager_load_paths
在开发中充当 autoload_paths
,在生产中充当急切加载.所有 app/*
目录都会自动添加到那里.
If the directory is under app/
, you don't need to add it anywhere, it should just work by default (definitely in 3.2.12). Rails has eager_load_paths
that acts as autoload_paths
in development, and eager load in production. All app/*
directories are automatically added there.
这篇关于将目录添加到 Rails 中的加载路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!