The project I’m working on was relying on Gems installed at the system level (as opposed to the user’s home directory), and I was beginning to find this less than optimal in terms of maintenance and people potentially upgrading (and breaking) those Gems.

So, I started investigating using Bundler for this part of my project. Bundler is already in use with the Rails part of the project, but I’m fairly new to Ruby, and therefore wasn’t sure how well Bundler would work for non-Rails code.

It turns out it’s really easy. Add a couple of lines to the top of your files, setup a Gemfile, and that’s pretty much it.

Unfortunately, I noticed that this wouldn’t work when I executed the Ruby script from outside the project directory. I was Googling frantically, finding a few other cases where people had a similar problem, but no resolution.

After leaving it for the weekend and coming back with a fresh perspective, I managed to dig up the BUNDLE_GEMFILE environment variable that Bundler uses. After a bit of experimentation, all I had to do was add ENV['BUNDLE_GEMFILE'] = '/path/to/Gemfile' before requiring Bundler in my code, and that seems to have worked.

A final note - if you’re subsequently running Ruby commands that use Bundler (or Gems) within your scripts, you may need to wrap those with a Bundler.with_clean_env do ... end block, to reset changes that Bundler makes to the environment.

It would be nice if this was more obvious (I think I ended up finding it in a manpage for bundle), but I’m glad it works nonetheless 😄