Cover by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

18.3. Requiring a Specific Version of a Gem

Problem

Your program depends on an interface or feature of a gem found only in particular versions of the library. If a user tries to run your program with the wrong version installed, you want to tell them which version you require, so they can upgrade.

Solution

The rubygems library defines a method, Kernel#require_gem, which is a kind of assertion method for gems. It will raise a Gem::LoadError if the given gem is not installed, or if no installed version of a gem meets your requirements.

The easiest solution is to allow any version of a gem; you don't need to use require_gem at all:

	require 'rubygems'
	require 'cmdparse'                               # => true

This is equivalent to requiring a minimum version of 0.0.0:

	require_gem 'nosuchgem'
	# Gem::LoadError: Could not find RubyGem nosuchgem (> 0.0.0)

If you can't use just any version of a gem, it's usually safe to require a minimum version, relying on future versions to be backwards-compatible:[2]

	require_gem 'cmdparse', '>= 1.0' #                          => false
	require_gem 'cmdparse', '>= 2.0.3'
	# Gem::LoadError: RubyGem version error: cmdparse(2.0.0 not >= 2.0.3)

Discussion

Although you may already be familiar with it, a brief review of the structure of version numbers is useful here. A version number for a Ruby gem (and most other pieces of open source software) has three parts: a major version number, a minor version number, and a revision number or build number (Figure 18-1).

Figure 18-1. Anatomy of a version number

Some packages have ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required