Note: This post is intended as a supplement to WTF Just Happened? A Quick Tour of Your First Rails App.
Gems and Bundler
A Ruby gem is a self-contained piece of code that performs a single piece of functionality. You can find gems for pretty much anything you could ever want; from extracting data into CSV format to integrating with Google analytics and everything in between! In fact, Rails itself is a gem. It is a gem for building web applications. See Rails: A Gem of Gems for more detail.
rubygems.org is a code library where most gems live. To add a gem to your Rails application, you add it to your
Gemfile. The syntax will look something like:
Gemfile assumes that any gem specified can be found at rubygems.org. To include a gem from elsewhere, such as github, you can do so as follows:
gem 'nokogiri', :git => 'https://github.com/tenderlove/nokogiri.git'
You can also specify a particular gem version, or range of versions. There are different syntax but the one you will most commonly come across is
~>, as in:
gem 'coffee-rails', '~> 4.2'
This is saying that we want the gem
coffee-rails that is the latest gem version of the form 4.2.x.
A Rails application contains a number of gems, some of which come with Rails, and others that you add to your application to provide additional functionality.
Each gem has dependencies and its version may only be compatible with certain specific versions of other gems. As we add more and more gems, keeping track of these dependencies can get very confusing. Bundler to the rescue!
Bundler is a tool (a gem, in fact) that looks at all the gems in your
Gemfile and figures out which version of each gem should be included to ensure they are compatible and will play nicely with each other. As Bundler is a gem, you can install it on your machine by running the following command:
gem install bundler
To invoke Bundler and install your gems you type the following command into your command line:
To update all your gems to their latest version, you run
bundle install (or
bundle update) creates a file called
Gemfile.lock. This file contains your entire dependency tree. When you check this into GitHub, and make it part of your application source code, you ensure that everyone running your application uses the exact same versions. This is very important for your application to behave the same on different machines.