Ruby, RVM, Gemsets and Bundler/Gemfiles

As a Drupal themer, we're often tasked with building multiple sites concurrently. One site may be a new build from scratch, and another could be a site built two years ago that is getting a new feature. If they utilize Sass in the theme, then they both have one thing in common:

They have Ruby gem dependencies.

What are they chances that both sites use the same versions of the same gems? Slim? None? Ever tried to build a set of Sass files when you don't have the correct gem versions installed? Oh what a pain.

Let's take the pain away with a few simple techniques.

Ruby and RVM

OS X comes with Ruby built-in, but I highly recommend installing Ruby with RVM. With RVM, you can specify the version of Ruby you want installed, plus a whole lot more. Installation instructions are available, but are outside the scope of this blog post.

Gemsets

One of the coolest things about using RVM, is the ability to have gemsets. According to the RVM website, "RVM gives you compartmentalized independent ruby setups." This means that you can have as many sets of gems as you'd like. I recommend having a separate gemset for each project/theme.

To create a gemset:

$ rvm gemset create name_of_project

Then use a gemset to make it active:

$ rvm gemset use name_of_project

Now you can install gems as you normally would.

To list the gemsets you have installed:

$ rvm gemset list

There are many more gemset commands, but these are the ones I use most.

Gemfiles and Bundler

"Bundler provides a consistent environment for Ruby projects by tracking and installing the exact gems and versions that are needed."

You must install the bundler gem in your new gemset:

$ gem install bundler

Now, in your theme, create a file called "Gemfile" and add the following on the first line:

source 'https://rubygems.org'

Add the primary gems you need to the Gemfile. Open up your browser, and navigate to https://rubygems.org. Then search for the gem you need for your project, and go to its page. On its page, there will be a black box half way down the page with the info you need for your Gemfile. For example, to use Compass in your project, add this to your Gemfile:

gem 'compass', '~> 1.0.1'

Continue adding the gems you need to the Gemfile. Once you've added all of them, we need to install them:

$ bundle install

This will download and install all of the gems you specified in your Gemfile, plus their dependencies. It also creates a file called Gemfile.lock. Gemfile.lock contains all the gems, and their versions, that were just installed.

Add both Gemfile and Gemfile.lock to your code repository.

Moving on...

If a new developer needs to be able to compile your sass files, all they will need to do is install them:

$ bundle install

This will install the gems and versions as specified in the Gemfile.lock file.

Profit!