Always run rake from a bundle

04 February 2013

Seen this error about a million times?

  You have already activated rake 1.5.1, but your Gemfile requires rake 1.4.4
  Consider using bundle exec. (Gem::LoadError)

This (usually) happens because the rake in your $PATH is different to the one that’s being included by bundler.

The ‘official’ solution is to use bundle exec. The slightly better solution is to run bundler with –binstubs. This creates a bin directory in the root of the project with the executables from all your gems. The caveat is you still have to remember to type bin/rake instead of rake.

Notice how you never run into this problem with the rails gem? That’s because rails is treated as a special case. The rails executable looks for a script/rails command and runs that instead.

Since 99% of people will only run into the above error with rake, I don’t see why it shouldn’t be a special case as well. Let’s make it one! Add this to your .bashrc or .profile

rake() {
  if [[ -e "./Gemfile.lock" ]] && `grep -q rake Gemfile.lock`; then
    echo "Running rake from bundle"
    command bundle exec rake "$@"
  else
    command rake "$@"
  fi
}

Now if you run rake from inside a project with Rake in the Gemfile, it will use bundle exec instead of using the rake in the path.