Rubocop as a Teaching Tool

November 04, 2015

Last year I jumped into a project that had started about 9 months earlier. The team had already defined best-practice patterns and decided on preferred syntax. It was also a Node.js project, something I was less familiar with at the time.

Fortunately JSLint was being used as part of the CI build. While frustrating at the beginning, it quickly taught me how the team preferred to write their code. Nobody handed me a style guide. I could write code, run the build, and get immediate feedback.

In about a week I was catching (most) syntax issues without even having to run the build. JSLint effectively taught me the style guide to follow.

When the next Ruby project started, I went looking for a similar tool and found Rubocop. I added it as a build step, just to see the impact it might have. Here are the results:

Rubocop Graph

Each bar represents how many commits out of 10 caused a Rubocop failure.

At first it failed all the time. You can start to see a pretty immediate drop about half way in. This is when we finally fixed the offenses that had already been introduced into the project. There were a lot of these because Rubocop was added after about 2 weeks of development had passed. From that point to present day, there's been a continuous downward trend in the number of offenses per commit.

This points to something interesting. As time has passed, there are fewer offenses introduced into the project that violate the style guide. For myself and the team that I work on, Rubocop has proven to be a pretty good teacher.

Setting Up Rubocop

Installing Rubocop in a Ruby project is easy. Add rubocop to your Gemfile, bundle install and you're ready to roll. If your project has been around for awhile, be prepared for that first run depression to set in. It happens.

To use Rubocop to enforce a style guide, I find it helpful to disable most of the metric cops. Sure, perceived complexity, method length, etc can be important. But in my opinion those are things best dealt with in code reviews rather than being enforced by almighty Rubocop.

In case it's helpful, the full .rubocop.yml from my recent project can be found here.

Lessons Learned

Introducing Rubocop into this project was a positive experience overall. The resulting codebase is both consistent and readable. A word of warning though: get buy-in from the team before you try this. Having a tool pointing things out in your code is annoying. Explain the purpose and ask for feedback.

It worked for us, give it a shot and let me know how it works out!

PREVIOUSLY all the things