How to run a ruby script within bundler context?

RubyBundle

Ruby Problem Overview


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.

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

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.

Solution 3 - Ruby

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

Solution 4 - Ruby

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichiel de MareView Question on Stackoverflow
Solution 1 - RubyDave NewtonView Answer on Stackoverflow
Solution 2 - RubyDorianView Answer on Stackoverflow
Solution 3 - RubyKornyView Answer on Stackoverflow
Solution 4 - RubyDavid MolesView Answer on Stackoverflow