views:

806

answers:

4

I need to store app specific configuration in rails. But it has to be:

  • reachable in any file (model, view, helpers and controllers
  • environment specified (or not), that means each environment can overwrite the configs specified in environment.rb

I've tried to use environment.rb and put something like

USE_USER_APP = true

that worked to me but when trying to overwrite it in a specific environment it wont work because production.rb, for instance, seems to be inside the Rails:Initializer.run block.

So, anyone?

A: 

I found a good way here

Ricardo Acras
+7  A: 

Look at Configatron: http://github.com/markbates/configatron/tree/master

I have yet to use it, but he's actively developing it now, and looks quite nice.

Bill Turner
Awesome +1..........
fig
+2  A: 

The most basic thing to do is to set a class variable from your environment.rb. I've done this for Google Analytics. Essentially I want a different key depending on which environment I'm in so development or staging don't skew the metrics.

This is how I did it.

In lib/analytics/google_analytics.rb:

module Analytics
  class GoogleAnalytics
    @@account_id = nil

    cattr_accessor :account_id
  end
end

And then in environment.rb or in environments/production.rb or any of the other environment files:

Analytics::GoogleAnalytics.account_id = "xxxxxxxxx"

Then anywhere you ned to reference, say the default layout with the Google Analytics JavaScript, it you just call Analytics::GoogleAnalytics.account_id.

Otto
+2  A: 

I was helping a friend set up the solution mentioned by Ricardo yesterday. We hacked it a bit by loading the YAML file with something similar to this (going from memory here):

require 'ostruct'
require 'yaml'
require 'erb'
#config = OpenStruct.new(YAML.load_file("#{RAILS_ROOT}/config/config.yml"))
config = OpenStruct.new(YAML.load(ERB.new(File.read("#{RAILS_ROOT}/config/config.yml")).result))
env_config = config.send(RAILS_ENV)
config.common.update(env_config) unless env_config.nil?
::AppConfig = OpenStruct.new(config.common)

This allowed him to embed Ruby code in the config, like in Rhtml:

development:
  path_to_something: <%= RAILS_ROOT %>/config/something.yml
webmat