Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 870
Tim Santeford Avatar asked Jan 24 '11 07:01

Tim Santeford


People also ask

What are config Initializers in rails?

An initializer is any file of ruby code stored under /config/initializers in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks and plugins are loaded.

What is application rb in Rails?

The configuration file config/application. rb and environment-specific configuration files (such as config/environments/production. rb ) allow you to specify the various settings that you want to pass down to all of the components. For example, you could add this setting to config/application.rb file: config.

What is Railties?

Railtie is the core of the Rails Framework and provides several hooks to extend Rails and/or modify the initialization process.


2 Answers

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.

like image 119
Julio Santos Avatar answered Sep 24 '22 02:09

Julio Santos


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! 
like image 23
Tyler Liu Avatar answered Sep 21 '22 02:09

Tyler Liu