Why do you need “require 'bundler/setup'”?

2020-02-26 14:35发布

In almost every Sinatra example I've seen, despite what it does, it always has the following two lines:

require 'rubygems'
require 'bundler/setup'

In most examples, removing the 'bundler/setup' require seems to have no breaking effect, so I'm confused about when/where I need to include this.

I hate using things without knowing exactly the reason for it being there, so I was hoping someone could explain why I need both lines and what they do?

标签: ruby bundler
4条回答
甜甜的少女心
2楼-- · 2020-02-26 14:54

There is a practical explanation:

Let's say we want to use a gem called pristine_text from the github master branch

Gemfile:

gem "pristine_text", github: "nurettin/pristine_text"

main.rb: (wrong)

require "pristine_text"
# error, can't find pristine_text

require can't find it, because the gem is not in a path ruby can see. If you look at the actual path of the gem, you will see that it is under

/pristine-text-some_commit_id

main.rb: (right)

require "bundler/setup"
require "pristine_text"
# no error

The error is gone, because now you load bundler with your dependencies' load paths.

查看更多
甜甜的少女心
3楼-- · 2020-02-26 14:59

The Bundle setup "clears" the load path, so the subsequent attempt to require something that is not in Gemfile will result of the load error.

查看更多
老娘就宠你
4楼-- · 2020-02-26 15:02

Understanding Bundler's setup process

Brian Storti wrote the best article I can find on Bundler setup - from which the quote is taken.

Understanding what is happening

To put it shortly, what Bundler is doing is removing from the $LOAD_PATH everything that is not defined in the Gemfile. The $LOAD_PATH (or just $:) is the global variable that tells Ruby where it should look for things that are required, so if a dependency is not in the Gemfile, it’s not going to be in the $LOAD_PATH, and then Ruby has no way to find it.

Show me the code

This is the file that is loaded when we require 'bundler/setup', and the important thing here is the Bundler.setup call. This setup first cleans the load path, and then activates just the gems that are defined in the Gemfile, which basically means adding them to the $LOAD_PATH variable.

Note: I've updated the "show me the code" links as they went to master branch which has changed.

查看更多
够拽才男人
5楼-- · 2020-02-26 15:09

It ensures you're loading Gemfile defined gems. Please have a look at the documentation here https://bundler.io/v1.12/bundler_setup.html

查看更多
登录 后发表回答