66

I have a Ruby script called foo.rb, and I want to run it within the context of the bundler environment. How?

bundle exec foo.rb doesn't work, because exec expects a shell script.

Michiel de Mare
  • 40,513
  • 27
  • 100
  • 132

4 Answers4

106

Pass the script name to the ruby command:

bundle exec ruby script_name

If you also want the Rails environment:

bundle exec rails runner script_name
Dave Newton
  • 152,765
  • 23
  • 240
  • 286
4

For instance, I wanted to use the same version of Rubocop as my Rails app and not the latest system one, so doing this in a script:

require 'bundler'
Bundler.require

# ...

Allowed me to use my app's version of rubocop.

Dorian
  • 19,009
  • 8
  • 108
  • 111
1

You can just make it a script - add

#!/usr/bin/env ruby

to the start of the file, and make it executable. Then bundle exec foo.rb will work as expected.

(This is on unix or OSX - not sure about Windows)

See http://bundler.io/v1.15/man/bundle-exec.1.html#Loading

Also see https://coderwall.com/p/kfyzcw/execute-ruby-scripts-directly-without-bundler-exec for how to run ruby scripts with bundled dependencies, without needing bundle exec

Korny
  • 1,918
  • 1
  • 18
  • 14
  • If you are using RVM I believe this does not work. I think it is loading ruby in the global or local context, not in the RVM context. And you have to use `bundle exec ruby script_name` in order to have it run in the RVM context. – John C. Feb 27 '21 at 22:53
0

If you want to create a script that you can run in bundle context within a project, you can invoke Bundler programmatically. E.g., given a project:

foo
├── Gemfile
└── bar
    └── baz.rb

you can put the following at the top of baz.rb to give it access to the gems in the Gemfile:

#!/usr/bin/env ruby

ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
require 'bundler/setup'

# ...etc.

With that, you can invoke the script directly without using bundle exec, and you also don't have to invoke it from within the project directory.

David Moles
  • 39,436
  • 24
  • 121
  • 210