Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby gem statement - what does it do?

Tags:

ruby

gem

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?

like image 465
wim Avatar asked Jan 14 '23 17:01

wim


2 Answers

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

like image 110
Arie Xiao Avatar answered Jan 22 '23 20:01

Arie Xiao


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.

like image 45
matt Avatar answered Jan 22 '23 20:01

matt