This is Anti-pattern—thoughts on programming and whatnot by Brandon Weiss.

Bundler.setup vs. Bundler.require

There are two ways to use Bundler to require Ruby dependencies: manually with Bundler.setup and automatically with Bundler.require.

Bundler.setup only sets up the load paths so that you can require your dependencies when and wherever you like.

# Gemfile
source "https://rubygems.org"

gem "sinatra"
gem "http"

# environment.rb
require "bundler"
Bundler.setup(:default)

require "sinatra/base"
require "http"

Bundler.require sets up the load paths and automatically requires every dependency, saving you from having to manually require each one.

# Gemfile
source "https://rubygems.org"

gem "sinatra", require: "sinatra/base"
gem "http"

# environment.rb
require "bundler"
Bundler.require(:default)

Bundler.setup and Bundler.require also take multiple gem groups as arguments, allowing you to conditionally load groups based on the environment.

# Gemfile
source "https://rubygems.org"

gem "sinatra", require: "sinatra/base"
gem "http"

gem "pry", group: "development"
gem "thin", group: "production"

# environment.rb
require "bundler"
Bundler.require(:default, ENV["RACK_ENV"].to_sym)
Avatar
Brandon Weiss
Programmer at Domus
Get new posts in your inbox
I post a few times a year about programming and whatnot. No spam.