Set Up Your Gemfile Dependencies Using Groups

Grouping your dependencies in your Gemfile

A typical rails app makes use of many gems. But is it necessary to install or add all of them to the load path? In most cases the answer is no.

Here is a typical example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
source 'https://rubygems.org'

gem 'rails', '4.1.7'
gem 'sass-rails', '~> 4.0.3'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'

group :development do
  gem 'sqlite3'
  gem 'pry-rails'
  gem 'factory_girl_rails', "~> 4.0"
end

group :test do
  gem 'sqlite3'
  gem 'factory_girl_rails', "~> 4.0"
  gem 'faker'
  gem 'rspec'
  gem 'rspec-rails'
  gem 'capybara'
end

group :production do
  gem 'pg'
end

The gems that are not listed in a group, are automatically part of the :default group. Organizing the gems in groups gives you different ways to run bundler.

1
$ bundle install --without production

The above will install gems for all the groups except the ones in :production. Also when running your rails app it will not load the gems in the :production group. Bundler will also remember this setting and next time you invoke bundle install will use the same setting.

You can find out more on the Bundler–Using Groups page.

Notice that the the sqlite3 and factory_girl_rails gems is in both :development and :test, you can dry that up as well, by removing them from those groups and adding them like this:

1
2
3
4
group :development, :test do
  gem 'sqlite3'
  gem 'factory_girl_rails', "~> 4.0"
end

Comments