Run a bundler-deployed Ruby app outside of its own directory?

There are some good answers here, but I thought I'd add a quick answer that works in my scenario, where I am explicitly setting up Bundler with a call to Bundler.require, and don't often execute the script via bundle exec.

If you are doing this, and the Gemfile/Gemfile.lock files are in the same directory as the script, you can use a combination of Dir.chdir and Kernel.__dir__ like so:

  Dir.chdir(__dir__) { Bundler.require }

This works by changing the directory for the call to Bundler.require (as this expects the relevant files to exist in the current working directory) before returning to the original directory.


You use bundler as gem manager for your app. I think in this case using bundle exec is the best way to run executables.

If you run your app from different directory than directory that contains Gemfile you should set Gemfile location by setting BUNDLE_GEMFILE (see bundle help exec). Following will help you:

BUNDLE_GEMFILE=/path/to/Gemfile bundle exec /path/to/runmyapp

Tackling a similar problem myself I ended up creating a wrapper script,

#!/bin/bash
BUNDLE_GEMFILE="$(dirname $0)"/Gemfile bundle exec ruby "$(dirname $0)"/app.rb $*

Here app.rb is the app's "main" entry point. You might call the wrapper script runmyapp or the app's name or whatever.

Note: $0 is set by bash to the wrapper script's file location, e.g. /home/foo/app/runmyapp or ./runmyapp

bundle exec "executes the command, making all gems specified in the Gemfile available to require in Ruby programs." (docs)