Why do you need "require 'bundler/setup'"?
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?
It ensures you're loading Gemfile defined gems. Please have a look at the documentation here https://bundler.io/v1.12/bundler_setup.html
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.
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.
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.
精彩评论