Gems, Gemfiles, and Bundler

What is a Gem?

A Gem is a bundle of code we can include in Ruby projects. This allows us to take someone else’s code and drop it into our own project. Gems can perform functionality such as:

  • Converting a Ruby object to JSON
  • Pagination
  • Interact with APIs such as Github

Jekyll itself is a Gem as well many Jekyll plugins including jekyll-feed, jekyll-seo-tag and jekyll-archives.

What is a Gemfile?

A Gemfile is Ruby’s dependency management system. It’s a list of Gems you want your Ruby project to run. We use Gemfiles on Jekyll sites when we have Jekyll plugins.

What a Gemfile Looks Like

source 'https://rubygems.org'

gem 'jekyll', '3.1.6'

gem 'i18n'
gem 'xkeys'
gem 'jekyll-sitemap'

A Gemfile requires at least one source which tells your project where to download the Gems. With rare exception this will be rubygems.org.

You need the word gem followed by the name of the Gem. You can include a version number if want a specific version.

Bundler and How We Use It

Bundler is the program which reads the Gemfile and downloads the Gems.

When we create or change a Gemfile, we need to run bundle install which performs two tasks:

  1. Creates a Gemfile.lock file if it doesn’t exist. This file is auto-generated and includes all the Gems in Gemfile with the addition of a version number even if it wasn’t specified. This feature ensures everyone working on the project has the same gem versions. It’s not a feature we use at Travel Tripper as we rebuild this file for every project using the latest version of all gems that don’t specify a version.
  2. Downloads the gems in Gemfile.lock.

Usually when we run jekyll we’d do something like this:

jekyll serve

When we’re using a Gemfile with restricted versions we need to run Jekyll with Bundler. We might have multiple versions of Jekyll on our computer and if we run jekyll serve, it might use the wrong version. We can solve this using bundle exec which makes only the Gems in the Gemfile available. For example if we want to run jekyll serve we’d run:

bundle exec jekyll serve

Using Gemfiles and Bundler ensures we have a consistent environment for our site.