Custom Gemfiles

When I’m writing or collaborating on a gem, I like to use a couple of useful lint tools every now and then. These are good for finding code smells, untested code or hinky syntax.

There are a bunch of them, not everyone will find the same ones useful, and they are not required in order to build or test the gem. They tend to be the sort of gem that is quite picky about which version of ruby you use.

So, what I like to do is split my custom gems that only I find useful off into a separate Gemfile:

source 'https://rubygems.org'
gemspec

# include local gemfile
local_gemfile = File.join(File.dirname(__FILE__), 'Gemfile.local')
instance_eval(File.read(local_gemfile)) if File.readable?(local_gemfile)

Then, in a Gemfile.local, anyone working on the project can put in their own ‘extras’. I put Gemfile.local into the project’s .gitignore file, but also provide a Gemfile.local.example file:

# Gems that are not necessary, but might be useful or a personal preference.
# Rename to Gemfile.local.

group :development do
  gem 'excellent'
  gem 'simplecov'
  gem 'cane'
  gem 'metric_fu'
  gem 'sandi_meter'
  gem 'guard'
  gem 'guard-minitest'
  gem 'pry'
  gem 'pry-byebug'
  # etc...
end

You can then pick your own set of gems that you want to work with.

We’re not done yet, though. Some of these gems require code in other parts of your gem. For example, to get code coverage reports when you run your tests, you need to add the following to a test helper:

require 'simplecov'

SimpleCov.start

However, if you add this into git, and someone else doesn’t use the simplecov gem, they’ll get a LoadError, and their tests will fail. To fix this, just rescue the error:

begin
  require 'simplecov'
  SimpleCov.start
rescue LoadError
  # simplecov not installed. We don't mind.
end
Tagged: | gems | idioms | gemfiles |