3

I'm currently using an initializer to load a config.yml file into an AppConfig hash which offers access to variables for the environment. For production I am using environmental variables set on the server. I am using the following code to fallback to the config variable if the environmental variables are not set (i.e in development and test).

ENV['FACEBOOK_API_KEY'] || AppConfig['facebook_api_key']

My problem is that I need some of these variables to be available in the environment-specific file (development.rb/production.rb etc), but this file is loaded before the initialzers. How should I deal with this?

Undistraction
  • 42,754
  • 56
  • 195
  • 331

2 Answers2

8

Have a look at the Rails guide for Configuration Initialization Events. There are events that you can hook into when doing this kind of configuration.

In short you can have configuration for the environment done after initialisation with:

#config/environments/development.rb
YourApp::Application.configure do
  config.after_initialize do
    #do some configuration after all initialisers have run
  end
end
Undistraction
  • 42,754
  • 56
  • 195
  • 331
roo
  • 7,106
  • 8
  • 39
  • 45
  • Thanks. That was exactly what I needed. Its actually after_initialize NOT after_initializion btw. – Undistraction Feb 13 '12 at 16:08
  • Ha - thanks. I was thinking of spelling initialise US style and my fingers decided to type initialization instead. – roo Feb 14 '12 at 03:17
0

If there's a way you can create a two-tier structure like database.yml you could always define separate configurations for each environment in the same file, then reference the appropriate version:

ENV['FACEBOOK_API_KEY'] || AppConfig[Rails.env] && AppConfig[Rails.env]['facebook_api_key']
tadman
  • 208,517
  • 23
  • 234
  • 262
  • 1
    Thanks, but that's actually what I'm doing, only I'm not using a separate hash for the environment as I won't ever need to store config values for more than one at a time. – Undistraction Feb 13 '12 at 16:07