Ruby On Rails 3 - AppConfig.yml
For each and every Rails app, I always needed some kind of app configuration file. Something simple, at best as a YML-file. With some research on google and stackoverflow I ended up with the following solution. It’s neither new nor groundbreaking and probably someone else has already done it that way.
This solution allows to:
- Have a “default” configuration
- For every environment changing some attributes
- No need to copy all attributes for every environment
- It allows nested attributes for easier access and better readability. (eg. homepage>head)
- It’s hashed
- You can access the AppConfig from everywhere in your rails app by using “AppConfig[:homepage][:head]”
(Tested with Rails 3.2.1)
New file at ‘config/app_config.yml’:
defaults:
homepage:
head: peterkling
subline: "webdesign: analyse | konzeption | gestaltung | umsetzung"
development:
homepage:
head: "peterkling [DEV]"
test:
production:
New file at ‘lib/appconfig.rb’:
config = ActiveSupport::HashWithIndifferentAccess.new(YAML.load_file("#{Rails.root.to_s}/config/app_config.yml"))
if !config[Rails.env].nil?
AppConfig = config[:defaults].deep_merge(config[Rails.env])
else
AppConfig = config[:defaults]
end
Add to environment.rb
load 'lib/appconfig.rb'
Access AppConfig eq. in views:
<h1><%= AppConfig[:homepage][:head]%></h1>
<h2><%= AppConfig[: homepage][:subline]%></h2>