Cleaning up a messy Gemfile

Aging Rails apps can become a bit of a mess. Fortunately we can fix this bit by bit. Today we will look at some rules for writing a clean, readable Gemfile.

1. The gems should be split into groups. (Test, Development, etc.)

Any Gemfiles that look like this can get messy as they get longer:

gem 'nokogiri'
gem 'sinatra'

gem 'wirble', group: :development
gem 'faker', group: :test
gem 'rspec', group: :test

gem 'capybara', group: :development
gem 'rspec-rails', group: :development

This can be as many groups as you like but they should be in this format:

# Gems used everywhere.
gem 'nokogiri'
gem 'sinatra'

group :development do
  gem 'wirble'
end

group :test do
  gem 'faker'
  gem 'rspec'
end

group :test, :development do
  gem 'capybara'
  gem 'rspec-rails'
end

2. Within those groups the gems should be alphabetically ordered.

This just makes sense so that they can be found easily. You wouldn’t want to walk into an unordered library, would you?

3. Remove any gems that have bee commented out.

You don’t need to keep the entire history of the Gemfile. That is what git is for.

4. No comments on it’s own line if the comment refers to a gem.

Comments in the Gemfile usually aren’t needed. You can learn what each of the Gems do. So instead of this,

# Thin. Web Server greatness
# Start with: rails s
gem 'thin'

let the comment sit on the line with the gem:

gem 'thin' # Start with rails s

5. Only use apostrophes or quotations marks, not both. Pick one and change the other.

You can pick between gem ‘rails’ or gem “rails” but the style should be consistent.

This isn’t a conclusive list but it should help cut down the size and complexity of your Gemfile.

Processing…
Success! You're on the list.