How To: Execute in a Bundler context

I’m writing a small* sinatra-based tool for running tedious command line tools in a nicer environment, and I came across this problem. I wanted to be able to run a tool, say RSpec, in the context of a particular Gemfile. This is the same behaviour as the `bundle exec rspec` command. I’ve spent the last couple of nights figuring it out, and I finally got it going with a little help from StackOverflow, so I thought I’d share it here.

To run a piece of code in a Bundler context, you first need to load up Bundler and the Bundler CLI:

require 'bundler/setup'
require 'bundler/cli'

You then need to set a special environment variable that Bundler reads when performing any actions. This is what gives Bundler its context:

ENV['BUNDLE_GEMFILE'] = "/path/to/Gemfile"

Once this is set, we’re in that particular Gemfile’s context. We can now execute code using that Gemfile’s gems, or we can run the internal Bundler exec method to execute a command:

Bundler::CLI.new.exec('rspec')

This will do the same thing as if we were on the command line, in the Gemfile’s directory, using the “bundle exec” command.

Pretty nifty, eh?

*I say small, it gets bigger every day.