Custom Configurations and App Specific Settings


One not immediately obvious Ruby on Rails configuration issue I came across is how to structure application-specific config parameters, and in particular, how to make them configurable/overridable across different environments (dev, test, production). This has been solved repeatedly in different ways by the Rails community and there's info scattered around but assimilating it took a while, here's what I've settled on for now.


I couldn't have said it better myself. I've now spent 4 hours researching the best way to do this...this is a basic feature of a web app, you'd think there would be a conventional way to create ..whatever you want to call them: custom configurations, application specific settings, application configs...in Rails.

At present, I've found four solutions...the one suggested by the above blogger, and these three others:

  • http://www.taknado.com/2007/7/25/custom-configuration-info-in-rails
  • http://jarmark.org/projects/app-config/
  • Use after_initialize method on the Rails::Configuration class. (Note: this is only semi-well documented...it's documented, but not included at http://api.rubyonrails.org. I found it here: http://edgedocs.planetargon.org/classes/Rails/Configuration.html#M002860)


In addition, I found these blog posts useful:


  • http://toolmantim.com/article/2006/12/27/environments_and_the_rails_initialisation_process
  • http://glu.ttono.us/articles/2006/05/22/guide-environments-in-rails-1-1


I haven't decided how I'm going to do this yet, but I hope you find this helpful.

UPDATE: I was exchanging e-mail from Jeff at softiesonrails.com who suggested this solution:
What I usually do is add it to the bottom of environment.rb. If I have RAILS_ENV-dependent data (like development mode vs. production mode), then just put the relevant Ruby code at the bottom of environments/development.rb, for example:

    module MyConstants
ALLOWED_NAMES = ['jeff', 'cookie monster']
IP_ALLOWED = '1.2.3.4'
end

and then you can access them anywhere in your Rails code as MyConstants::ALLOWED_NAMES, etc.

If you prefer to move it to a file, you'd create a file named my_constants.rb in the /lib folder, and then explicitly require it from environment.rb:

    require 'my_constants'

No comments: