Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are bundle exec and require 'bundler/setup' equivalent?

Tags:

ruby

bundler

Do these things accomplish exactly the same?

  • starting a ruby process with bundle exec ruby foo.rb
  • having require "bundler/setup" as the first line of foo.rb
like image 863
Michiel de Mare Avatar asked Jun 20 '12 09:06

Michiel de Mare


1 Answers

In your specific example they can be considered the same, however in reality they are not the same.

bundle exec makes some changes to the environment that bundler/setup does not make. If your foo.rb never runs a subshell, or never tries to run other ruby executables in subshells, then both versions are equivalent (they will both load bundled gems correctly and work exactly the same).

The whole idea with bundle exec is to enable you to run executables that were not originally designed with bundler in mind. Like rspec, rails, rackup. If your own app (foo.rb) does not try to run such executables that might be dependent on your bundles, then it makes no difference either way. Since all you want to make sure with bundler is that you load the correct gems, and for that bundler/setup works exactly as expected in your case.

From the bundler docs when talking about running ruby system executables:

In some cases, running executables without bundle exec may work, if the executable happens to be installed in your system and does not pull in any gems that conflict with your bundle.

However, this is unreliable and is the source of considerable pain. Even if it looks like it works, it may not work in the future or on another machine.

Then from the manpage of bundle exec you can get some additional clues as to what bundle exec actually does:

ENVIRONMENT MODIFICATIONS

  • make sure that it's still possible to shell out to bundle from inside a command invoked by bundle exec (using $BUNDLE_BIN_PATH)
  • put the directory containing executables (like rails, rspec, rackup) for your bundle on $PATH
  • make sure that if bundler is invoked in the subshell, it uses the same Gemfile (by setting BUNDLE_GEMFILE)
  • add -rbundler/setup to $RUBYOPT, which makes sure that Ruby programs invoked in the subshell can see the gems in the bundle

So if you build your app with bundler support in mind, then you never need to bundle exec your app.

But if you need to use other tools that load your app code that might load gems before they load your app code (which then might pull in a wrong non-bundled gem), then you need to use bundle exec.

like image 152
Casper Avatar answered Nov 18 '22 19:11

Casper