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.
Pingback: Last Week’s Top Ruby News: Rails 3.1.3, autoload deprecated, and conferences
Pingback: Chris Oliver » Rails Tip #1: Clean Configuration Values
Pingback: Community News Round Up | New Relic blog
Pingback: Trevor Turk — Links for 12-9-2011
Pingback: Ruby On Rails (2): Links, News and resources « Angel “Java” Lopez on Blog
Pingback: Ruby’s Singleton and Custom Rails Application Configuration | Coding Daily