Code Reviewing a Ruby on Rails application.
Tags: ruby, webdev, programming, tutorial
Published: 2023-07-03 11:00:00

Ruby is a programming language that is often praised for its simplicity, elegance, and expressiveness. Just like any other programming language, it's important to focus on writing good quality code to ensure that the applications we build are reliable, scalable, and easy to maintain. Writing high-quality, maintainable Ruby code is essential for developing applications. Performing regular code reviews and using code quality tools can help catch problems early and improve your code over time. This article explores some of the best options for Ruby code reviews and quality analysis.

### Table of Contents
{%- # TOC start -%}

- [Importance of Code Review in Ruby on Rails Development](#importance-of-code-review-in-ruby-on-rails-development)
  * [Maintain code quality](#maintain-code-quality)
  * [Improve collaboration](#improve-collaboration)
  * [Reduce bugs](#reduce-bugs)
  * [Opportunities for refactoring](#opportunities-for-refactoring)
  * [Share knowledge](#share-knowledge)
  * [Performance issues are identified](#performance-issues-are-identified)
- [Common Challenges in Ruby on Rails Code](#common-challenges-in-ruby-on-rails-code)
  * [Performance bottlenecks](#performance-bottlenecks)
  * [Scalability concerns](#scalability-concerns)
  * [Security vulnerabilities](#security-vulnerabilities)
  * [Code readability problems](#code-readability-problems)
  * [Dependency management](#dependency-management)
  * [Database migration issues](#database-migration-issues)
- [Tools for Ruby on Rails Code Review](#tools-for-ruby-on-rails-code-review)
  * [RuboCop](#rubocop)
  * [Reek](#reek)
  * [Brakeman](#brakeman)
  * [RSpec](#rspec)
  * [Flay](#flay)

{%- # TOC end -%}

## Importance of Code Review in Ruby on Rails Development

Code reviews are an important practice in software development that can:

### Maintain code quality

By having another set of eyes review the code, issues like inefficient algorithms, poor variable names, unnecessary complexity, and bad practices can be caught and corrected before the code is merged. This helps maintain a consistent code style and quality standard.

### Improve collaboration

The code review process involves a discussion between reviewers and authors, sharing knowledge and best practices. This fosters communication and collaboration between team members.

![Best Practices to Ensure Better Code Quality of Your Software in 2023](https://mobisoftinfotech.com/resources/wp-content/uploads/2022/01/og-code-quality.png)

### Reduce bugs

Catching bugs early during code reviews is much cheaper and faster than fixing them later after the code has been merged and released. This significantly improves software reliability.

![6 Proven Tips To Prevent Software Bugs For Developers](https://www.bigscal.com/wp-content/uploads/2022/08/6-Proven-Tips-To-Prevent-Software-Bugs-For-Developers.png)

### Opportunities for refactoring

Reviewers may spot opportunities to refactor or restructure code in a more maintainable way. This can improve the design and architecture of the codebase over time.

![7 Code Refactoring Techniques in Software Engineering - GeeksforGeeks](https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200922214720/Red-Green-Refactoring.png)

### Share knowledge

Junior developers can learn good coding practices and design patterns by reviewing the code of more experienced developers, and vice versa.

![Encouraging Teamwork Through Knowledge Sharing - ASPHN](https://asphn.org/wp-content/uploads/2019/12/encouraging-teamwork-through-knowledge-sharing.jpg)

### Performance issues are identified

Reviewers may spot performance bottlenecks, inefficient algorithms or resource usage issues that impact performance. These can be addressed before the code is merged.

![Website Performance & Health Monitoring: Tips & Best Practices](https://www.searchenginejournal.com/wp-content/uploads/2022/10/website-performance-and-health-monitoring-635945792a855-sej.png)

## Common Challenges in Ruby on Rails Code

When working with Ruby on Rails code, developers often face various challenges that can impact the overall quality of their applications. These challenges can range from performance bottlenecks and scalability concerns to security vulnerabilities. Addressing these common challenges is crucial.

Here are some common challenges developers face when working with Ruby on Rails code:

### Performance bottlenecks

Performance bottlenecks in Ruby on Rails occur when certain parts of the code or system architecture significantly slow down the application's performance. Let's consider an example to illustrate this:

```ruby
# Slow query due to inefficient use of ActiveRecord
@users = User.all
@users.each do |user|
  user.orders.each do |order|
    # Perform some calculations or operations on each order
  end
end

# Optimized query
@users = User.includes(:orders)
@users.each do |user|
  user.orders.each do |order|
    # Perform some calculations or operations on each order
  end
end
```

The above-unoptimized code, makes a separate database query to fetch each user's orders, resulting in N + 1 queries total where N is the number of users.

The optimized code uses [eager loading](https://www.allerin.com/blog/eager-loading-inwith-rails) to fetch all user data and all order data in 2 queries. This reduces the number of queries from N + 1 to a constant number, improving performance.

### Scalability concerns

As traffic and data volumes increase, Rails applications can struggle to scale vertically on a single server. Scaling horizontally across multiple servers and databases requires additional configuration and tooling.

### Security vulnerabilities

Like any framework, Rails has had security vulnerabilities over the years that require patching. Developers must keep dependencies up to date and follow secure coding practices.

### Code readability problems

Rails aims for convention over configuration, but this can result in "magic" that makes the code less readable for new developers. Over time, the codebase can become cluttered and difficult to navigate.

### Dependency management

Rails has a large number of dependencies that must be managed and kept up to date. Outdated dependencies can introduce security vulnerabilities or cause compatibility issues.

### Database migration issues

Rails uses Migrations to manage database schema changes, but over time these can become complex and difficult to maintain. Schema refactoring may be required.

## Tools for Ruby on Rails Code Review

### RuboCop

[RuboCop](https://docs.rubocop.org/) is a Ruby static code analyzer (a.k.a. `linter`) and code formatter. Out of the box it will enforce many of the guidelines outlined in the community [Ruby Style Guide](https://rubystyle.guide/). Apart from reporting the problems discovered in your code, RuboCop can also automatically fix many of them for you.

```bash
rubocop                                # Check entire project
rubocop --auto-correct                 # Automatically correct offenses
rubocop --only Rails/ActionFilter      # Check specific cop
```

{% youtube https://www.youtube.com/watch?v=sfOGjcMVQ9U %}

#### Benefits 

- Enforces a consistent Ruby style across the codebase. This makes the code easier to read and maintain for other developers.

- Finds potential bugs and errors early. RuboCop will detect issues like syntax errors, unused parameters, missing translations, etc.

- RuboCop rules can catch issues that make tests fragile or hard to write.

- Consistent code style across a Rails app makes it easier for new developers to understand and maintain the codebase.


### Reek

[Reek](https://github.com/troessner/reek) is a code smell detection tool for Ruby that helps identify potential design issues. It analyzes your codebase and provides feedback on areas that might benefit from refactoring or improvement. Here's an overview of what Reek is and how to use it:

```bash
reek app/                                  # Check whole app directory
reek -c reek.yml app/models/*.rb           # Check models with config
```

![GitHub - troessner/reek: Code smell detector for Ruby](https://opengraph.githubassets.com/187baac8e516274a2e32a4628ec25f8c7dc2a032e5148d702dfb3032f15fb15e/troessner/reek)

#### Benefits

- Reek analyzes your Ruby code and detects potential problems like feature envy, long parameter lists, etc. This helps catch issues before they become serious problems.
- By reducing code smells, Reek helps make your Rails code more readable and easier for new developers to grasp.
- For detected code smells, Reek can provide concrete suggestions to improve the code.

### Brakeman

[Brakeman](https://brakemanscanner.org/) is a static analysis security vulnerability scanner for Ruby on Rails applications. It finds potential security issues in Rails applications by examining the Ruby code. Brakeman helps find and fix security holes before deploying your Rails app.

```bash
brakeman                          # To run brakeman
brakeman your_rails_app           # Add path of the folder
brakeman -A                       # To run all the checks
brakeman -q                       # To suppress informational warning
```

{% youtube https://youtu.be/DHHHnPwSY5I %}

### Benefits

- Brakeman analyzes your Rails code to detect common security issues like SQL injection, XSS, remote code execution, and more.

- Brakeman has checks for vulnerabilities that are specific to Ruby on Rails like mass assignment, unsafe redirects, and strong parameters.

- By identifying and fixing vulnerabilities, Brakeman helps make your Rails app more secure.

- Manually scanning code for security issues is time-consuming. Brakeman automates most of this work.

### RSpec

[RSpec](https://rspec.info/) is a testing framework for Ruby that is widely used in the Ruby on Rails community. It allows developers to write and execute automated tests. RSpec promotes [behavior-driven development](https://en.wikipedia.org/wiki/Behavior-driven_development) (BDD) by providing a readable syntax for describing the expected behavior of the application.

```bash
bundle exec rspec                   # Run all spec files
bundle exec rspec -fd               # Run specs with failures/pending
bundle exec rspec path/to/spec.rb   # Run specific spec
```

{% youtube https://www.youtube.com/watch?v=-uhFA74eBG0 %}

#### Benefits

- RSpec uses a natural English-like syntax that makes specs easy to read and understand.

- With automated tests, developers get faster feedback on whether code changes broke any functionality. This speeds up development.

- RSpec's plugin architecture makes it easy to extend the framework with custom matchers, helpers, and more.

### Flay

[Flay](https://github.com/seattlerb/flay) analyzes ruby code for structural similarities. Differences in literal values, names, whitespace, and programming style are all ignored. Flay helps reduce code duplication and keep your code DRY (Don't Repeat Yourself).

```bash
flay .             # Analyzes the code within the current directory
flay --diff .      # Shows a side-by-side diff of the duplicated code
```

![flay, a linter for Ruby - Rating And 47 Alternatives | Analysis Tools](https://ik.imagekit.io/analysistools/flay_https_3A_2F_2Fruby.sadi.st_2FFlay.html_rS3Inq4vnl.jpg)

#### Benefits

- Flay can detect duplicated methods, classes, and blocks of code that could be refactored into a shared method or module.

- By identifying duplicated code, Flay helps developers reuse existing code rather than duplicating it. This reduces maintenance effort.

- You can set the similarity threshold above which Flay will report a possible duplication.

- For duplicated code, Flay can suggest ways to extract that code into a shared method or module.

- As your Rails codebase grows, Flay continues to find new duplicated code that can be improved.

### Wrapping up

In conclusion, code reviews are essential for high-quality Ruby on Rails applications. They catch issues early, improve consistency and transfer knowledge between developers. Though time-consuming initially, code reviews save much more time by reducing bugs and improving maintainability. Start small with partial code reviews and expand coverage over time as the team adapts. The benefits to code quality, productivity and sustainability make code reviews a best practice for any Rails development process. Implementing regular code reviews should be a top priority for any team-building.


Let's agree that Code Review is important in RoR environments and every software project. Documatic already has some articles that you can check below: 

{% embed https://dev.to/documatic/the-art-of-code-review-1lo4 %}
{% embed https://dev.to/documatic/effective-techniques-for-code-review-in-software-engineering-29i0 %}
{% embed https://dev.to/documatic/5-code-refactoring-techniques-to-improve-your-code-2lia %}
{% embed https://dev.to/documatic/improve-code-quality-with-these-tips-and-best-practices-2mh2 %}
{% embed https://dev.to/documatic/top-6-php-code-quality-tools-2023-2kb1 %}

If you want more articles on similar topics just let me know in the comments section. And don't forget to ❤️ the article. I'll see you in the next one. In the meantime you can follow me here:

{% user j471n %}

![](https://res.cloudinary.com/practicaldev/image/fetch/s--haJKPmN9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://media0.giphy.com/media/65ODDoEMHM5wbGDHWT/giphy.gif%3Fcid%3Decf05e472rut0ytp29eznos4focko84kmq33u4btpu74cw1w%26rid%3Dgiphy.gif align="center")