Rubocop

This week I thought I would write a short entry about a tool that I have found really useful for fixing the many syntax errors I have been making in my first few months programming Ruby.

This comes in the form of a syntax-checking gem called Rubocop. It enforces the guidelines in the community Ruby style guide: https://github.com/bbatsov/ruby-style-guide

I found this useful because, although I had read the style guide, before I started using Rubocop I think I was so concerned about getting the program to work, that I kind of neglected making the syntax correct. So every time I opened a pull request my boss would have to write comments about how the indentation etc was all wrong. So I think he especially has found that Rubocop has been a very helpful, one because he doesn't have to spend as much time telling me my syntax is wrong, and two because Rubocop now seems like 'the bad guy' instead of him, for pointing out my errors.

I think after using Rubocop and Ruby in general for a little while now, my knowledge of the syntax has got way better, mostly because you get tired of having to correct the same mistakes over and over again to make Rubo happy, so eventually you just stop making them.

To learn how to install Rubocop: https://github.com/bbatsov/rubocop

But basically in the terminal you need to run:

gem install rubocop

You then navigate into the directory that you want to check your code syntax for. You can then just run:

rubocop

This will check all the ruby files in the directory. Or you can run:

rubocop name_of_file.rb

which will check a specific individual file.

If you find you really like it, you could even add it as a pre-commit hook: https://github.com/jish/pre-commit

I can demonstrate how Rubocop works using a snippet of code that I wrote as a rake task to spell check blog posts for the company website. The whole Rakefile is quite long so that is why i'm just using this bit to demo... hence why it starts on line 3. I have purposefully messed up the syntax...

Snip20140530_13

So using the terminal I navigate into the directory that this Rakefile is saved in and run:

rubocop Rakefile

Which then outputs:

Snip20140530_14

Snip20140530_15

So as you can see from the first offence:

Rakefile:3:6: C: Prefer single-quoted strings when
you don't need string interpolation or special symbols.

desc "Spell checks blog posts"

In line 3 of the code it wants me to use ' ' rather than “”

I can then work through each offence, fix it, and then run Rubocop again to check that it has been fixed.

You can also make some changes to the rules that Rubocop enforces, in this case I didn't want it complaining that lines were too long. So in the root of my project directory I created a hidden file called .rubocop.yml and set the line length to 120:

Snip20140530_16

Now my code looks like this:

Snip20140530_19

and Rubocop returns the magical:

Snip20140530_18