rubocop is the de-facto standard tool when it comes to checking for coding style violations in your Ruby (on Rails) projects. It’s configurable and integrates with most editors via plugins.

And even though I’m using an integration for my editor of choice, Atom, sometimes it happens to me that I commit code that’s violating our coding styles. That’s kind of embarrassing and sets me back a couple of minutes each time (waiting for a CI run, checking GitHub, fixing the violation, waiting for CI again,…).

Wouldn’t it be nice to guard myself against this issue? May I present to you: pronto and git hooks!

pronto allows you to run different static code analysers on the changes you’ve made. git hooks allow you to execute arbitrary code before certain actions take place, like running a script before you do a commit.

Add the pronto and pronto-rubocop gems to your development group in your Gemfile (I like this one better than executing a globally installed version of pronto, as it makes sure behaviour is the same across machines):

# Gemfile

group :development do
  gem 'pronto'
  gem 'pronto-rubocop', require: false

Now create a new file named pre-commit inside your git hooks directory and paste the following content:

# .git/hooks/pre-commit

bundle exec pronto run --exit-code

Make the file executable with chmod +x .git/hooks/pre-commit.

From now on, whenever you are trying to commit code that’s not adhering to your Ruby style guide (as defined by your .rubocop.yml file), you will not be able to commit and instead see a message like this:

$ git commit
app/controllers/books_controller.rb:18 W: Useless assignment to variable - `a`.