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

前端 未结 4 1751
名媛妹妹
名媛妹妹 2020-12-24 10:43

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 initiali

相关标签:
4条回答
  • 2020-12-24 10:55

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

    # aaa.rb
    require_relative 'bbb'
    # ... code using values from bbb.rb ...
    
    0 讨论(0)
  • 2020-12-24 11:05

    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.

    0 讨论(0)
  • 2020-12-24 11:07

    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
    
    0 讨论(0)
  • 2020-12-24 11:12

    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!
    
    0 讨论(0)
提交回复
热议问题