I think I have a basic understanding of what require/include statements at the top of a ruby script are doing, like
require 'rspec'
These statements are easy to google and find relevant results. But sometimes I have seen a gem statement like
gem 'rspec'
What does this line do?
In ruby code, gem(gem_name, *requirements)
defined in Kernel
tells Ruby to load a specific version of gem_name
. That's useful when you have installed more than one version of the same gem.
For example, if you have installed two versions of rspec
, say 2.12.0
and 2.13.0
, you can call gem
before require
to use specific version. Note that gem
should come before the require
call.
gem 'rspec', '=2.12.0'
require 'rspec'
A gem 'gem_name'
without version uses the latest version on your machine, and that's unnecessary. You can call require
without gem
to get the same behavior.
And besides, in Bundler::Dsl, gem
is used to tell bundler to prepare/install specific version of ruby gems. You'll see that in Gemfile
The original behaviour of require
, before Rubygems, was to search all the directories listed in the $LOAD_FILES
variable for the file, and to load the first one it finds that matches. If no matching file was found, require
would raise a LoadError
.
Rubygems changes this process. With Rubygems, require
will search the existing $LOAD_PATH
as before, but if there is no matching file found then Rubygems will search the installed gems on your machine for a match. If a gem is found that contains a matching file, that gem is activated, and then the $LOAD_PATH
search is repeated. The main effect of activating a gem is that the gems lib
directory is added to your load path. In this way the second search of the load path will find the file being required.
Normally this will mean that the latest version of a gem that you have installed gets activated. Sometimes you will want to use a different version of a gem, and to do that you can use the gem
method. The gem
method activates a gem, and you can specify the version you want, but doesn’t require any files. When you later require the files you want, you’ll get them from the gem version you specified.
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