Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

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.

I found a good way here

Use environment variables. Heroku uses this. Remember that if you keep configuration in the codebase, anyone with access to the code has access to any secret configuration (aws api keys, gateway api keys, etc).

daemontool's envdir is a good tool for setting configuration, I'm pretty sure that's what Heroku uses to give application their environment variables.

I have used Rails Settings Cached.

It is very simple to use, keeps your configuration values cached and allows you to change them dynamically.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top