Monday, February 18, 2008

RubyGems Explicit Versioning

One of the most useful features of RubyGems as a package manager is the ability to force explicit versions of the packages in your ruby code. Unfortunately worst than not being documented this feature is wrongly documented even in RubyGems own manual pages.

So for the record here is how to tell your ruby code to use a specific gem version:

For RubyGems version < 0.9.4 we use:



1 require 'rubygems'

2 require_gem 'mechanize','=0.4.7'

3 require 'mechanize'



What we do is call "require_gem" to set up the version we want and then load the gem using "require".

After RubyGems 0.9.4 onwards the "Kernel#require_gem" method was deprecated and replaced with "Kernel#gem". So if you have the latest RubyGems the code above becomes:



1 require 'rubygems'

2 gem 'mechanize','=0.4.7'

3 require 'mechanize'



Instead of using "=0.4.7" it is also possible to use "<0.4.7" or ">0.4.7" if the specific version is not required.

We can be more professional and make our scripts handle both cases above using the Gem::RubyGemsVersion constant:



1 require 'rubygems'

2 if Gem::RubyGemsVersion < "0.9.4"

3     require_gem 'mechanize','=0.4.7'

4 else

5     gem 'mechanize','=0.4.7'

6 end

7 require 'mechanize'



This way our code will (hopefully) work with all versions of RubyGems.

References:
http://redhanded.hobix.com/inspect/autorequireIsBasicallyGoneEveryone.html
http://piao-tech.blogspot.com/2006/11/tips-on-rubygems-installation-and.html

No comments:

Post a Comment