81

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.

4 Answers 4

128

Pass the script name to the ruby command:

bundle exec ruby [script_file_name]

If you also want the Rails environment:

bundle exec rails runner [script_file_name]
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, that was pretty obvious in retrospect.
@MichieldeMare It's like why everything is in the last place you look--because you stop looking ;)
7

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.

Comments

5

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.

Comments

3

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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.