Rails: Application-Specific Config File
If there’s one thing I hate in programming or web design, it’s having to repeat myself. So I always do my best to abstract out repeated bits of information and put them in a single, easily changeable location. A nice way to do this in Ruby on Rails is to create your own YAML config file.
First create the config file in config/config.yml
(or any other name), and then we’ll get it loaded. Here’s the kind of thing I generally put in the file:
# config.yml - custom config file for app-specifics, loaded in environment.rb
app_name: FiletOFish
tag_line: It has fewer calories, because it's fish
copyright: Copyright 2010 Too Much Tea, LLC
Next we’ll get it loaded by adding a new file to config/initializers/
. After the framework itself, gems, and plugins are loaded, Rails runs the code in every file in this directory. So make a new file called config/initializers/load_config.rb
, and put the following line in it:
APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")
All set! You’ll need to restart your Rails server if you have it running as it doesn’t pick up configuration changes automatically. Now we’re ready to use the APP_CONFIG
variable, in a view, for instance:
<div id="header">
<h1><%= APP_CONFIG['app_name'] %></h1>
<span id="tag_line"><%= APP_CONFIG['tag_line'] %></span>
</div>
I can’t recall where I picked up this trick, so I’m sorry if I failed to credit you. Better props next time?