Rails with_options in your config file

You’ve probably seen the with_options method (part of ActiveSupport) used in the context of routing maps such as:

map.with_options :controller => "people" do |people|
    people.connect "/people",     :action => "index"
    people.connect "/people/:id", :action => "show"
end

But realize that with_options extends the Ruby Object class (source code) so it can be used practically in any context.

I’d like to keep my configuration file leaner when specifying gem dependencies.

config.with_options(:source => 'http://gemcutter.org') do |c|
  c.gem 'acts_as_fu'
  c.gem 'factory_girl' 
  c.gem 'mocha' 
  c.gem 'redgreen'
  c.gem 'shoulda'
  c.gem 'test_benchmark'
end
 
# not yet in gemcutter 
config.gem 'stubble'

However, the gotcha is the Rails::Configuration class is loaded before ActiveSupport. So if you’d like to use with_options in your config, be sure you load the module environment.rb before the Rails::Initializer block is hit.

require 'active_support'

The above is moot with the new gem bundling features in Rails 3, read more.


About this entry