Do you use RAILS_ENV in your Rails app to execute different code depending on the environment you’re running?
1 2 3 4 5 |
|
No? Ok, great. Yes? Ok, not so great.
Those from both camps are likely to get something out of this post, so read on.
The problem with using RAILS_ENV in your code has 2 main issues.
- If you misspell the environment string (RAILS_ENV == ‘developent’) you won’t be notified of any errors or warnings and you may introduce bugs or other issues into your code (if your tests don’t catch it)
- You’re integrating details of a specific environment into the code when your app logic should have no knowledge of what environment it is currently running in.
Solution (Partial)
Introduce configuration details for your app in the environment files and use those in your app.
1 2 3 4 5 6 7 8 |
|
This keeps the code logic clean from environment specifics and if you spell the variable incorrectly, you’ll get an error, which is nice.
Solution (The whole 9 yards)
The partial solution can work, but it’s far from ideal.
You can’t specify default values cleanly for your app and then override a configuration value for a specific environment; things get worse if you introduce additional environments. Specifying a default value in environment.rb and then providing an override in development.rb (for example) doesn’t really work without some some ugly hacks. The reason for this is that these new options don’t work in the same way the existing Rails configuration options do in the environment files.
So how about we use the Rails configuration functionality with our own options?
Not possible? Well, lets write a plugin to make it possible. Wait a second, lets first check if somebody else has solved this problem for us.
http://agilewebdevelopment.com/plugins/app_config BAM!
Before I found this plugin, I scoped out the basic details in my head for how I’d implement my own plugin to enable this new functionality, but no use reinventing the wheel, so I did a quick search first and I was extremely happy to see that this plugin implementation was pretty much identical to what I was thinking, so even better.
Using the plugin, I can now specify my options as follows.
1 2 3 4 5 6 7 8 |
|
What the plugin introduces is an additional configuration value called app_config where you can specify any option you like and then in the code you access these options with the AppConfig value.
Now we also get all of the niceties of the Rails configuration functionality!
See the plugins README file and its code for additional details on using this handy plugin.