Simple Application Config in Rails

One thing I inevitably end up needing on every Rails project is application-specific configuration — usually just a few variables that need to vary by environment. There are a few ways to accomplish this, so I'll enumerate the obvious choices here before showing favor.

Constants in the environment

This is the easiest. Just place a constant in each environments/<env>.rb:

HOSTNAME = "swig505.com

On the "pros" side, this method is clearly the easiest. On the "cons", it requires programmer diligence across multiple files to ensure that each environment has each constant set. Also, there's no single place to look at all the variables since they are strewn across multiple source files, usually intertwined with other unrelated code. I think we can do better.

Third-party Gems

As Ruby developers, we've become accustomed to an active open-source community. If you have a specific problem, chances are that someone else has hit the same thing, and subsequently solved it (as they saw it), open-sourced it, and released neatly packaged gem. Head on over to Ruby Toolbox's Configration Category and check out the solutions others have come up with. There's quite an array of options, and most likely there's one that works well for you. As far as I'm concerned, this should be the first place you look — no need re-inventing the wheel, eh?

Write your own as an initializer

Honestly, application configurations are pretty darn simple. Just create an config/application.yml and stick all your configuration variables in there (a la database.yml). You get the power of YAML to define more complex structures like hashes and arrays, and its already the Rails-y way of doing configs. After that, the code is pretty darn simple to parse and access it, so let's just throw it in an initializer and piggyback off the our application module. Here's a quick version:

This exposes the config variables as both a hash-like accessor as well as methods on a new singleton Config within your application module. Using the above, you would then access variables like:

MyRailsApp::Config.hostname

Conclusion

If you can't already tell, my bias is toward using a simple initializer. This problem seems simple enough that we don't need to create another third-party dependency (gem), and I always make mistakes keeping everything synced between environments when using constants. So there you have it!

blog comments powered by Disqus