In my current project based on Ruby on Rails framework, I need to store application specific configuration somehow. There are several approaches I’ve found in Internet: AppConfig plugin, several methods described on the HowtoAddYourOwnConfigInfo wiki page, but neither one looks “config-like”. Me with my friend, Alexey Kovyrin, discovered all of them and decided to use YAML-file as a configuration format. In my opinion, the ideal configuration file looks like this:
1 2 3 4 5 6 7 8 9 10 11 | common: support_email: [email protected] root_url: myhost.com photos_max_number: 6 production: email_exceptions: true development: root_url: localhost:3000 photos_max_number: 10 |
In this example you can see three sections: common will be used as a base configuration for all environments, production and development — environment specific options. Optional sections are production, development, and testing, or any other custom environment name. I’ve placed this file in config/config.yml and created lib/app_config.rb which looks like this:
1 2 3 4 5 6 7 8 | # Load application configuration require 'ostruct' require 'yaml' config = YAML.load_file("#{Rails.root}/config/config.yml") || {} app_config = config['common'] || {} app_config.update(config[Rails.env] || {}) AppConfig = OpenStruct.new(app_config) |
Now I’m able to use constructions like AppConfig.support_email
and AppConfig.root_url
. Looks like I’ve kept all my configs as DRY as possible :-)