Ruby gem activation

Posted on November 14, 2024 by Riccardo

This is how you use a Ruby gem usually:

require 'foo'
Foo.bar

For the require to work, the gem needs to be available on the LOAD_PATH:

ruby -e 'puts $LOAD_PATH'

The act of adding a gem to the LOAD_PATH is called "activating a gem".

In a vanilla Ruby situation, you can add a directory to the LOAD_PATH with:

ruby -I ./foo/lib -e "puts(require 'foo')"
# true

More often, you deal with a bundle that contains a Gemfile:

gem 'foo'

To activate the gems from the Gemfile (taking into account the versions from Gemfile.lock):

require 'bundler/setup'
require 'foo'

or (equivalent):

require 'bundler'
Bundler.setup
require 'foo'

Notice that the setup step will first clear the LOAD_PATH and activate only the gems in the bundle.

For example, Rails does it here and here.

If you've ever wondered what the hell is up with bundle exec ..., the answer is simple: Bundler activates the gems in the bundle with something like

RUBYOPT="-rbundler/setup" ruby ...

Of course, things are more complex than that. But this should give you a starting point.

Bundler: How to use Bundler with Ruby

PinkLetter

It's one of the selected few I follow every week – Mateusz

Tired of RELEARNING webdev stuff?

  • A 100+ page book with the best links I curated over the years
  • An email once a week full of timeless software wisdom
  • Your recommended weekly dose of pink
  • Try before you buy? Check the archives.