5 (+1) Useful Tools to Detect Smells in Ruby on Rails
Tools don’t make good code, good programmers make good code.
Nobody wants to live in a smelly house, if it smells, for sure something wrong is happening, so you need to detect where the smell comes from and eradicate it. The same happens for an app, like a Ruby on Rails project, it’s a good practice to detect “smelly” code and refactor it.
“If it smells bad, change it.” @Kent Beck
Luckily, there are some gems out there that can help.
Rubycritic gives you a deep analysis of any single file in your project. Every file takes a grade from A (good) to F (bad) and a value for churn, complexity, duplication and smells.
It outputs an html file with a handy interface to navigate through the code and read all the notes (complex methods, duplicated code, etc…).
Rubocop is another code analyser. It has many ‘cops’, each cop is a different check that will be performed on your code. Cops can be added (i.e. https://github.com/nevir/rubocop-rspec) and configured.
The best way to manage all the options is to use the .rubocop.yml configuration file, like the one I use (I disabled some checks):
Metrics/LineLength:
Enabled: false
Documentation:
Enabled: false
It can also be integrated with your favourite editor, there are plugins for many editors out there, I personally use it with Sublime Text.
Pronto is useful to run analysis comparing different branches or pull requests. You need to install the runners you need (there’s a list of pronto runners).
$ gem install pronto
$ gem install pronto-reek
$ pronto run
So you'll get an analysis of committed changes, or you can do
$ pronto run — index
to run an analysis of uncommitted changes. I usually run the last one before committing.
Reek is a smell detector tool. Easy to use
$ gem install reek
$ reek .
The tool has many options and can run on a specific folder or file. Reek is included in rubycritic and can be included in pronto as well, so you don't need to use it if you already use any of those tools.
Rails Best Practices is a code metric tool, it checks your code against a collection of best practices and gives back a report.
It can be added in pronto so you don't need to run different tools.
Last, but not least, I recommend using Code climate.
It’s not just a tool, like the others, but an online service that checks the code for quality, security and test coverage. It needs access to your git account, can also check against different branches.
There’s also a code climate cli you can use locally in your machine
Now you're ready for the refactoring (because your code is covered by tests, right?)