How do I change the load order of initializers in Rails?

Ruby on-Rails

Ruby on-Rails Problem Overview


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!

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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 - Ruby on-Rails

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 - Ruby on-Rails

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 - Ruby on-Rails

Use a require_relative to make sure one file is loaded first.

# aaa.rb
require_relative 'bbb'
# ... code using values from bbb.rb ...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTim SantefordView Question on Stackoverflow
Solution 1 - Ruby on-RailsJulio SantosView Answer on Stackoverflow
Solution 2 - Ruby on-RailsTyler LiuView Answer on Stackoverflow
Solution 3 - Ruby on-RailsnoomerikalView Answer on Stackoverflow
Solution 4 - Ruby on-RailsPeter J. HartView Answer on Stackoverflow