Linting Ruby on Rails with Rubocop

When you are working on a relatively large team of engineers, it is important that your code is easy to read and understand in order to keep momentum and not be slowed down by trivial mistakes in your codebase. In order to achieve this, you would need to not only maintain, but also enforce some kind of style guide on your codebase. Naturally the question of how to do this will arise. This is where Rubocop comes into the picture.

Rubocop is a static analysis tool that checks whether or not your codebase adheres to the ruby community style guide.

Installing Rubocop

Simply add the rubocop gem to your Gemfile and run bundle install.

You should be good to go at this point. Rubocop will enforce all the rules in the ruby community style guide right out of the box. However, you might find that some of these rules do not quite align with in-house coding conventions. If this is the case you’ll want to add a .rubocop.yml file to the root of your project. Here you can specify any rules or cops that you want to enable or disable. Here is an example of what your rubocop.yml file might look like:

Take a look at these open source rubocop.yml files if you need inspiration some inspiration on where to start.

Working with Rubocop

Working with Rubocop is quite simple. If you use a relatively modern text editor, it’ll probably have with a linter plugin. I personally find Atom’s linter to be just the right blend of usefulness and unobtrusiveness. Rubocop will check the file every time you save it.

Rubocop in Atom

You can also use Rubocop on the command line. Here is a sample of the output I got when I ran rubocop on the file above.

Rubocop on the CLI

If neither the Command Line Interface nor the Text Editor are viable options for you, you can always use Guard to perform the checks for you.

Benefits of Rubocop

  • It’s easy to fix trivial mistakes during the development process, saving precious time in team code review sessions.
  • It’s easy to find your way around a large codebase if style is consistent.

There you have it. Rubocop is a simple and effective way to keep your projects clean and have one less thing to worry about during code review.