Rails 3 自动加载 [英] Rails 3 autoload
问题描述
我有一个类 ConstData:
I have a class ConstData:
class ConstData
US_CITIES = ['miami', 'new york']
EUROPERN_CITIES = ['madrid', 'london']
end
它存储在/lib/const_data.rb 下
Its stored under /lib/const_data.rb
这个想法是在模型、控制器或视图中我可以做到:
The idea is that inside a model, controller or view I can do:
ConstData::US_CITIES
获取 US_CITIES 等
ConstData::US_CITIES
to get the US_CITIES etc
Rails 应该自动加载这个类,我从:http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/662abfd1df9b2612?hl=en
Rails should load this class automatically, I got this from: http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/662abfd1df9b2612?hl=en
然而这行不通.谁能解释我如何做到这一点?
However this does not work. Can anyone explain me how to accomplish this ?
推荐答案
@daniel 所指的帖子是 2008 年的.Rails 从那以后发生了变化.
事实上,最近.Rails3 不会自动加载 lib/目录.
The post @daniel refers to is from 2008. Rails has changed since then.
In fact, quite recently. Rails3 doesn't load the lib/ directory automatically.
不过,您可以很容易地重新激活它.打开 config/application.rb
并在配置中(在 Application
类中)添加以下内容:
You can reactivate it quite easily though. Open config/application.rb
And add, in the config (in the Application
class) the followin :
config.autoload_paths += %W(#{config.root}/lib)
然后你的 lib/目录将被自动加载.
Then your lib/ dir will be autoloaded.
这篇关于Rails 3 自动加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!