jamesdlivesinatree
jamesdlivesinatree

Reputation: 720

Rails: Have initializer load before application.rb

I have an initializer named _settings.rb that looks like this

class Settings < Settingslogic
    source "#{Rails.root}/config/application.yml"

    namespace Rails.env
end

My application.yml defines a value for a custom setting I call environhost. I call it using:

   Settings.environhost

This works fine, EXCEPT for when I try to call the value in my /app/config/application.rb

config.action_controller.asset_host = Settings.environhost

For this, I get an uninitialized constant.

Is there anyway I can put a pointer in my application.rb to load _settings.rb before

 config.action_controller.asset_host = Settings.environhost

is loaded? What's the best way to do this?

http://guides.rubyonrails.org/initialization.html

Upvotes: 4

Views: 2625

Answers (1)

Billy Chan
Billy Chan

Reputation: 24815

Rails own configuration will be always loaded before any custom things, that's for sure. Otherwise can you imagine what a mess :)

The solution is not to try to load before Rails configuration. Instead, hook into initializer to add your own logic to override Rails default.

Railtie is the place you can do that without sweat. Here you can access config method shared in all initializers including Rails.

module MySettings
  def self.environhost
    "foobar"
  end

  class MySettingsRailtie < Rails::Railtie
    config.action_controller.asset_host = MySettings.environhost
  end
end

Side note: In most cases you should be fine to set assets host as mu_is_too_short commented. If you need anything other than that, you can use custom intializer by Railtie.

Upvotes: 2

Related Questions