From the gemfile man page, I learned there are two ways to import the gems you specified in the Gemfile
. The bundle.setup
will "setup adds gems to Ruby's load path" while bundle.require
will require all the gems.
What's the difference between these two methods? In which condition should I use one of them?
Bundler. setup only sets up the load paths so that you can require your dependencies when and wherever you like. Bundler. require sets up the load paths and automatically requires every dependency, saving you from having to manually require each one.
The commands bundle & bundle install also have the same functionality. bundle uses Thor, and bundle 's default task is install . Also, bundle i does the same thing as bundle install because bundle 's task i is mapped (aliased) to install .
bundle update and bundle install can both install the gems you specified in Gemfile but missing in gems. But bundle update does one thing more to upgrade: If the gems specified in Gemfile don't have version, it will upgrade to whatever latest.
Bundler provides a consistent environment for Ruby projects by tracking and installing the exact gems and versions that are needed. Bundler is an exit from dependency hell, and ensures that the gems you need are present in development, staging, and production. Starting work on a project is as simple as bundle install .
Bundler.setup
modifies the LOAD_PATH, so you can do things like require 'some_gem'
and they will work. It allows you to require gems 'by hand'. Before Bundler, using Rubygems, you would achieve much of the same effect doing require 'rubygems'
.
Bundler.require(:default)
on the other hand actually requires all the gems in the Gemfile (assuming you're not using groups; otherwise it requires those in the specified groups if you provide arguments). It is a shorthand for a bunch of require 'some_gem'
statements.
See http://gembundler.com/rationale.html. Note that they say you have to do require 'bundler/setup'
before doing Bundler.require
, but in practice this usually is not necessary. I almost never use Bundler.setup
(or require 'bundler/setup
), because I require all gems via Bundler.require
).
You must use Bundle.setup
and you can use Bundle.require
.
The main point of bundler is to make sure that exactly the Gems defined in the Gemfile are made visible to the application, i.e. all the gems mentioned there in exactly the mentioned versions, but not one more. To do that, the load path is adapted. This is done by Bundle.setup
.
To actually use the gems, they have to be required and thus loaded into the application. This can either be done by hand using a number of require
statements or automatically for all the gems listed in the Gemfile (or only some groups) using Bundle.require
. This however is only possible after adapting the loadpath as mentioned above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With