1

I am working on learning Ruby and one thing that I have seen in several instances and cannot understand are scripts that start with the keyword gem.

An example can been seen in the Sensu code.

gem "amqp", "1.3.0"

require "amqp"

require File.join(File.dirname(__FILE__), "base")

I understand the require statement for accessing another gem, but what does the exact gem "amqp", "1.3.0" mean?

Chris Powell
  • 175
  • 3
  • 7

1 Answers1

3

This is the gem method that Rubygems adds to Kernel (Rubygems is required by default in current Ruby versions). It activates a specific version of a gem (version 1.3.0 of the amqp gem in this case), meaning that the gems lib dir (or whatever dirs the gem specifies) is added to your LOAD_PATH, as are the lib dirs of any dependent gems it has.

It also checks that there are no version incompatibilities with any already activated gems.

All gems are activated when you use them. This normally happens when you call require. Calling gem activates the gem but doesn’t require any files from it, hence the line require "amqp" below (note the difference between amqp the gem, which the gem method refers to, and amqp the file, which is contained in the amqp gem and is what the require method is refering to).

This method is used to ensure you are using a specific version of a gem, without needing to use Bundler (or something similar). Bundler also has a gem method used in Gemfiles, but this is a different (but similar) method.

It’s also used to specify that you want to use the gem version of a library that is also part of the standard library (say if you want to use a more recent version). For example the Yaml library distributed with Ruby is Psych which is also available as a gem.

matt
  • 78,533
  • 8
  • 163
  • 197