How do I change the load order of initializers in Rails?
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?
Thanks!
Solution 1:
Rename the initializer to 01_name.rb
, that will force it to load alphabetically previously.
Edit
To quote the official Rails Guide for configuration (thanks zetetic for the tip):
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.
Solution 2:
Put the configuration code in config/environment.rb file, right after the first require statement, such as:
# 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!
Solution 3:
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
E.g.
# application.rb
module YourApp
class Application < Rails::Application
config.before_initialize do
# initialization code goes here
end
end
end
Solution 4:
Use a require_relative to make sure one file is loaded first.
# aaa.rb
require_relative 'bbb'
# ... code using values from bbb.rb ...