Ruby-on-rails 如何更改 Rails 3 中初始化程序的加载顺序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4779773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I change the load order of initializers in Rails 3?
提问by Tim Santeford
I have an initializer that loads configuration settings from a yaml file. I need to use these settings in other initializers. The settings are not being seen by the initializers that need them. What I think is happening is the settings are getting loaded too late. How do I guaranty that my configuration initializer gets loaded first? Is it un-rails like to have initializers depend on another?
我有一个从 yaml 文件加载配置设置的初始化程序。我需要在其他初始化程序中使用这些设置。需要它们的初始化程序看不到这些设置。我认为正在发生的是设置加载太晚了。如何保证我的配置初始值设定项首先加载?初始化器依赖于另一个是非轨道式的吗?
Thanks!
谢谢!
回答by Júlio Santos
Rename the initializer to 01_name.rb, that will force it to load alphabetically previously.
将初始化器重命名为01_name.rb,这将强制它之前按字母顺序加载。
Edit
编辑
To quote the official Rails Guide for configuration(thanks zeteticfor the tip):
引用官方的Rails 配置指南(感谢zetetic的提示):
If you have any ordering dependency in your initializers, you can control the load order by naming. For example, 01_critical.rb will be loaded before 02_normal.rb.
如果您的初始值设定项中有任何排序依赖项,您可以通过命名来控制加载顺序。例如,01_critical.rb 将在 02_normal.rb 之前加载。
回答by Tyler Long
Put the configuration code in config/environment.rb file, right after the first require statement, such as:
将配置代码放在 config/environment.rb 文件中,紧跟在第一个 require 语句之后,例如:
# Load the rails application
require File.expand_path('../application', __FILE__)
# Load global configurations
CONFIG = Hashie::Mash.new YAML.load_file(Rails.root.join("config", "application.yml"))[Rails.env]
# Initialize the rails application
RailsSetup::Application.initialize!
回答by noomerikal
Even though the guide recommends prepending the initializer filenames with numbers, that does seem ugly. Another way is to utilize the provided initialization hooks. See http://guides.rubyonrails.org/configuring.html#initialization-events
尽管指南建议在初始化文件名前加上数字,但这看起来确实很丑陋。另一种方法是利用提供的初始化钩子。请参阅http://guides.rubyonrails.org/configuring.html#initialization-events
E.g.
例如
# application.rb
module YourApp
class Application < Rails::Application
config.before_initialize do
# initialization code goes here
end
end
end
回答by Peter J. Hart
Use a require_relative to make sure one file is loaded first.
使用 require_relative 确保首先加载一个文件。
# aaa.rb
require_relative 'bbb'
# ... code using values from bbb.rb ...

