RubyGuides
Share this post!

Rubocop – Your personal code reviewer

Rubocop is a static analysis tool that will help you keep your code void of a number of style and potential error issues. It is very easy to get started, install rubocop using ‘gem install rubocop’.

rubocop

Now move to the project folder you want to analyse and run rubocop -l. The -l option tells it to only use the linter module, this will skip a lot of stuff like “extra spaces between parenthesis” and keep the output a lot more manageable for now.

Now you can get started cleaning those up. Since rubocop provides file name and line number, finding that code shouldn’t be a problem. If you are feeling brave, rubocop includes an autocorrect feature (option -a).

You can also disable or set your own rules via configuration files (YAML format). For details on that, I recommend trying the –auto-gen-config option and reading the ‘Configuration’ section of the README.

Other output formats

You may find that the output is a bit verbose, in that case you will be happy to know there are multiple output formats available. One that I like is the ‘simple’ format. You can enable this format with rubocop -f simple.

Other useful formats are: json (-f json), HTML (-f html), and summary (-f offenses). For the html version you will need to redirect the output to a file. Like this: rubocop -l -f html > rubocop.html

Integrating rubocop into your workflow

Hopefully you found that rubocop is a great tool and you would like to integrate it into your workflow. You have a couple of options, you could try using something like guard or a git pre-commit hook. You could also use an editor plugin, if you are using atom you could try out the linter-rubocop package.

You might also like:
Ruby string formatting

1 comment
tvinky says a couple of years ago

Rubocop is really great, I have been using it with Sublime and now I have added it to VIM. Really helps out with great suggestions 🙂

By the way, like the style which you are using in this blog – not so much text, simple examples. Thanks for posting!

Comments are closed