Peter Marklund

Peter Marklund's Home

Tue March 20, 2007
Programming

Rails Tip: Declare your Gem versions

Many Rails applications have external dependencies in the form of RubyGem libraries. The problem with such external dependencies is that you need to make sure that you have the right gem versions installed across all your servers, i.e. development, staging, and production. The probably easiest way around this is to freeze gems into your source tree. For rails you can use the Rake task "rails:freeze:gems" and you can freeze other gems by using Rick Olsen's Gems plugin.

At the end of the day there may still be external gems that you depend on, maybe because they need to be compiled, or maybe because you want to avoid your application source tree growing too big. You can fix the version of Rails using the RAILS_GEM_VERSION constant in environment.rb. For other gems you can fix the versions by adding statements like the following to your environment.rb:

gem "RedCloth", "3.0.4"

The gem command specifies that we will be using a gem of a certain version and it will attempt to add that gem to the load path (activate it), but not require it. If the gem version is missing you will be alerted on server startup.

So how do you know which gems you are depending on? One way might be to look at the load path. The following expression will return a list of Gems that have been activated so far in your application:

$:.map { |path| path[/^#{ENV['GEMS_PATH']}\/([^\/]+)/, 1] }.compact.uniq

You can inquire about a certain gem on your system using "gem list" and "gemwhich":

$ gem list|grep RedCloth
RedCloth (3.0.4, 3.0.3)
    RedCloth is a module for using Textile and Markdown in Ruby. Textile

$ gemwhich RedCloth
/usr/local/lib/ruby/gems/1.8/gems/RedCloth-3.0.4/lib/RedCloth.rb

Also, don't forget that if the gem comes with RDoc you can access that documentation by invoking gem_server on the command line.

Comments

Mathias Stjernström said over 7 years ago:

Great stuff Peter!
I actually faced these issues last week.

I solved it by using Geoffrey Grosenbach freeze other gems rake task
http://nubyonrails.com/articles/2005/12/22/freeze-other-gems-to-rails-lib-directory

But i did not know that you could specify required version to the gem command, thats sweet.

Cheers!

--------------------------------------------------------------------------------