I still see people promoting various gems and plugins to handle miscellaneous configuration elements for your application. One little known secret is that Rails 3 allows you to define your own configuration elements trivially.
In this case, I wanted to use the nifty wkhtmltopdf
utility to create a PDF. I was able to call the binary just fine with Homebrew on OSX but found that I had to use a custom binary checked into git for our production environment on Heroku. So I created a configuration variable to store where wkhtmltopdf
could be found in the current environment.
First, we define a default value for all environments in config/application.rb
:
module Configurator class Application < Rails::Application # By default, let OSX resolve the path to the binary config.wkhtmltopdf = "wkhtmltopdf" end end
Then we override the default setting as necessary in config/environments/
:
Configurator::Application.configure do # Settings specified here will take precedence over those in config/application.rb # Point Heroku explicitly to the binary we need to use config.wkhtmltopdf = "#{Rails.root}/bin/wkhtmltopdf" end
Lastly, we access the configuration element in our code:
cmd = [Configurator::Application.config.wkhtmltopdf, url, tmpfile.path]
Yes, that’s it. Just use Rails’s environment support and config
to store your own configuration elements. They’re trivial to set, trivial to access and require no third-party gems or custom text files.