How to Improve Code Quality on a Ruby on Rails Application
Tags: ruby, rails
Published: 2021-11-11 21:45:59

---
title: How to Improve Code Quality on a Ruby on Rails Application
published: true
description: Taking ages to deliver small changes? Constantly sacrificing code quality? Is it possible to ever pay off tech debt? Yes, it is! Learn which Ruby code quality tools you can use to perform static code analysis and improve code quality. This post is a summary of Ernesto Tagwerker's 'Trapped in the Tar Pit?' talk.
tags: ruby, rails
cover_image: https://www.hexdevs.com/images/posts/pexels-egor-kamelev-1685537.jpg
canonical_url: https://www.hexdevs.com/posts/code-quality-ruby-on-rails/
---

Does it take forever to ship even small features on the codebase you're working on? Is the code hard to understand and maintain? 
Are projects always running over budget? Are you constantly sacrificing code quality and not paying down technical debt?

When you change one feature, does another completely unrelated part of your app stop working? New bugs appear, even though tests never break? 🥵

Those are signs that you are suffering from working on a codebase with low code quality.

How can you get out of this mess? Is it possible to avoid getting into this situation in the first place? Yes, it is!

By the end of this post, you'll know exactly:

- How to improve Code Quality on a Ruby on Rails application
- Which Code Quality tools to use
- How to use the [Ruby Code Quality Checklist](#rails-code-quality-checklist) to get out of the tar pit

This post is based on a talk from Ernesto Tagwerker's talk entitled [Escaping The Tar Pit](https://www.youtube.com/watch?v=ZyU6K6eR-_A) at RubyConf 2019. Ernesto is the Founder & CTO at [FastRuby.io](https://www.fastruby.io/) & [Ombu Labs](https://www.ombulabs.com/).

## What is Code Quality?

> "Software Code Quality means it works as expected AND it isn't a PITA to maintain it" -- Ernesto Tagwerker

The simplest way to know if your codebase has enough Code Quality is if your team can easily add or change features without breaking 
unrelated features.

And when the features do break, the test suite easily detects the problem before you even push the code to production.

In summary, a quality codebase is **easy to read, change, and maintain**. It also has good code coverage, and the test suite helps you improve and refactor the code, or change features with confidence.

## How To Improve Code Quality on a Ruby on Rails application

There are four steps you need to follow:
- [Measure and Assess Code Quality](#how-to-measure-code-quality-on-a-ruby-on-rails-application)
- [Measure Code Coverage with SimpleCov](#how-to-calculate-code-coverage-with-simplecov)
- [Calculate Churn and Complexity with RubyCritic](#how-to-measure-code-quality-with-rubycritic)
- [Use Skunk to identify which files need urgent care](#how-to-find-code-smells-and-calculate-stink-score-with-skunk)

## How to Measure Code Quality on a Ruby on Rails Application

You don't necessarily need a tool to assess Code Quality, and there is no silver bullet. You'll always need to evaluate what the data means. The tools help guide you so you can make the best decisions by yourself 💫

Below are some tools and services to quickly assess code quality. You can use paid services such as CodeClimate, Codacy, and CodeScene to give you some measurements and reports.

Or, use open sources tools to help you perform static code analysis, calculate code coverage and point out code smells and refactoring opportunities.

Here's a list of tools you can use:
- [Coverage](https://ruby-doc.org/stdlib-3.0.2/libdoc/coverage/rdoc/Coverage.html): Ruby's built-in tool that provides coverage measurements for Ruby.
- [SimpleCov](https://github.com/simplecov-ruby/simplecov): a code coverage analysis tool for Ruby.
- [RubyCritic](https://github.com/whitesmith/rubycritic): a gem that wraps around static analysis gems such as Reek, Flay, and Flog to provide a quality report of your Ruby code.
- [Skunk](https://github.com/fastruby/skunk): a tool that helps you find the most complicated parts of your application that also have low code coverage.
- [Rubocop](https://github.com/rubocop/rubocop): a Ruby static code analyzer and formatter, based on the community Ruby style guide. 

## How to Calculate Code Coverage With SimpleCov

Use [SimpleCov](https://github.com/simplecov-ruby/simplecov) to generate a report of how many statements are covered by your test suite. It won't assess the test suite quality, though.

It will affect your test suite performance, so make sure to only run it when necessary.

## How to Measure Code Quality With RubyCritic

Ernesto recommends [RubyCritic](https://github.com/whitesmith/rubycritic) because it's a gem for assessing code quality that it's still actively maintained.

RubyCritic provides a score based on churn and complexity. These metrics help you identify files that are great candidates for refactoring.

Check out the talk at the minute [17:47](https://youtu.be/ZyU6K6eR-_A?t=1067
) to see how Ernesto analyzes the report generated by RubyCritic:

## How to Find Code Smells and Calculate SkunkScore with Skunk 🦨

A SkunkScore is an assessment combining code smells, code complexity, and code coverage.

[Skunk](https://github.com/fastruby/skunk)'s main goal is to serve as a compass for the first steps in your refactoring adventure. Focus on the files with a high skunk_score with a decent code_coverage score. That means you can get started with files that have code quality problems but also have tests, which makes this step easier.

Make sure to add a reminder to add more tests to the other files with high skunk_score and low code_coverage 📌

**Tip**: When working on new features, run `$ skunk -b main` against your feature branch to give you an idea of the features you're adding are improving or decreasing the code quality.

## Ruby on Rails Code Quality Checklist

Now that you have gathered the code quality data, use this checklist to start moving out of the tar pit 🏊‍♀️

### 1. Delete unused files with Coverband 🪦

The best code is no code, right? Dead code is code that is never executed and is just filling up space. In larger or older applications, dead code can be a very common thing.

Find dead code with [Coverband](https://github.com/danmayer/coverband), which can be run in production.

Or add a ["tombstone"](https://www.youtube.com/watch?v=29UXzfQWOhQ) inside a method you want to remove, push it to production and wait. Check again in a few weeks or months, and if the code is never executed, you can safely remove it.

Here are some other libraries to detect dead code:
- [Tombstone](https://github.com/lewispb/tombstone/)
- [Scythe](https://github.com/michaelfeathers/scythe)
- [Debride](https://github.com/seattlerb/debride)

### 2. Refactor the complex files with better code coverage first 💇‍♀️

Refactor complex files that have at least 60% or more code coverage.

Sandi Metz's ["Polly Want a Message"](https://www.youtube.com/watch?v=YtROlyWWhV0) talk has an approach for refactoring classes with lots of responsibilities.

**Tip**: Compare code quality improvements by running `$ skunk -b main`. It will show you how much it improved. Such a great metric to share with your team! 🎊

### 3. Write tests for the files with high skunk_core and low code coverage 🧹

Writing tests will decrease a file's skunk_score. Skunk gives you a list of good candidates for your next test-writing efforts.

Keep track of Code Quality by analyzing the SkunkScore Average. It's recommended to run the report every 3 weeks to evaluate the team's engineering practices and if the project is moving in the right direction.

### 4. Celebrate tiny wins often 🥳

Improving code quality is a hard task! Make sure to celebrate every tiny improvement along the way with your team. Enjoy the relief of working on a great Ruby codebase.

-------------------

We highly recommend you watch the talk. The best part of this talk is to feel like there's hope and that getting out of a tar pit is possible.

The questions he asked such as "What is code quality anyway?" are helpful to change the perspective on how to approach technical debt more humanely.

After all, technical debt has the name technical in it but it's more a result of social/cultural problems in a team.

Judging past decisions is easy and unhelpful. That's our default. Embracing the challenge and being open to the opportunities for improvement is the real challenge.

Now, go follow the checklist to assess your Ruby Code Quality and create a livable environment for your code.

---------

We watched Ernesto's talk at a previous [Watch Party](/watch-party). We host tech talks watch parties every 4 weeks, on a Saturday morning 📺

Sign up for our [newsletter](https://www.hexdevs.com/newsletter/) to get an invitation for when we host our next one:Saturday morning 📺

-----

Copyright 2021 hexdevs