Keeping your Ruby Style Consistent with Rubocop

I like coding style guides. Having a consistent style removes that little bit of friction that writing code in multiple styles creates. This article is a quick tutorial on how to get Rubocop - a static code analyzer for Ruby - up and running.

Installation in a Rails project

group :development do
gem "rubocop", require: false
end

Running Rubocop

To get a sense of the style violations in your project, simply run the 'rubocop' command from the command line.

  > rubocop

You might have an overwhelming number of violations, especially if bringing Rubocop into an existing project. Rubocop has a really nice feature that allows you to acknowledge the violations, but push them off into their own file to tackle at a later time. To invoke this feature, run Rubocop with the --auto-gen-flag to create the .rubocop_todo.yml

  > rubocop --auto-gen-config

The rubocop_todo.yml creates a list of all of your violations. You can then reference this file from your .rubocop.yml settings file, wiping the slate clean, ignoring violations for the time being.

inherit_from:
- .rubocop_todo.yml

Then, simply remove a single rule from .rubocop_todo.yml, rerun the 'rubocop' command (without the --auto-gen-flag), and fix the presented violation. Rinse and repeat until you have a clean project.

If you find that you disagree with a given rule, you can override the rule in your .rubocop.yml file. Let's say that I like double quotes better than single quotes. Simply add:

Style/StringLiterals:
EnforcedStyle: double_quotes
SupportedStyles:
- single_quotes
- double_quotes

It can be a little tricky to identify which violation comes from which rule, but a little bit of searching through the .rubocop_todo.yml should do the trick. I think it would be nice to have a table of Rubocop violation messages along with the rule that presents the message, to help pair the two.

That is it, simple and effective!