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:
1 2 3 4
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:
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:
1 2 3 4
I can’t recall where I picked up this trick, so I’m sorry if I failed to credit you. Better props next time?