RuboCop comes built-in with Rails 8.0

railsFebruary 14, 2024Dotby Alkesh Ghorpade

Maintaining clean, readable, and consistent code in web development is paramount. Ensuring that code remains maintainable as projects grow in complexity becomes increasingly challenging. This is where tools like RuboCop come into play, helping maintain code quality and enforce best practices.

Rails 8 adds Rubocop by default to new apps. RuboCop is a linter for Ruby designed to follow the community style guide. In this blog post, let's explore how Ruby on Rails developers can benefit from integrating RuboCop into their workflow.

What is RuboCop?

RuboCop is a widely used static code analyzer and formatter for Ruby. It enforces the principles and guidelines outlined in the Ruby Style Guide, ensuring that your code follows best practices and remains consistent across your project. By analyzing your codebase for potential issues, style violations, and performance bottlenecks, RuboCop helps you write cleaner, more maintainable code.

Before Rails 8.0

Integrating RuboCop with Rails

Integrating RuboCop into your Rails project is straightforward. First, you'll need to add the RuboCop gem to your Gemfile:

gem 'rubocop', require: false

After adding the gem, run bundle install to install RuboCop and its dependencies. Once installed, you can generate a default .rubocop.yml by manually creating it or running the below command.

rubocop --auto-gen-config

The above command will generate the output below and two new files: .rubocop_todo.yml and .rubocop.yml.

$ rubocop --auto-gen-config
Added inheritance from `.rubocop_todo.yml` in `.rubocop.yml`.
The following cops were added to RuboCop, but are not configured. Please set Enabled to either `true` or `false` in your `.rubocop.yml` file.

Please also note that you can opt-in to new cops by default by adding this to your config:
  AllCops:
    NewCops: enable

Gemspec/DeprecatedAttributeAssignment: # new in 1.30
  Enabled: true
Gemspec/DevelopmentDependencies: # new in 1.44
  Enabled: true
Gemspec/RequireMFA: # new in 1.23
  Enabled: true
Layout/LineContinuationLeadingSpace: # new in 1.31
  Enabled: true
..................................................
..................................................
..................................................
Inspecting 264 files
..................................................
..................................................
264 files inspected, 182 offenses detected, 86 offenses autocorrectable
Created .rubocop_todo.yml.
..................................................
..................................................

The .rubocop.yml file in the root directory of your Rails project contains a set of default rules and configurations. You can customize this file to tailor RuboCop's behaviour to suit your project's needs.

In Rails 8.0

With Rails 8, you don't need to add the rubocop gem explicitly. Since RuboCop is added in Rails 8, a .rubocop.yml will exist by default.

It can be skipped by passing the --skip-rubocop flag.

To know more about this feature, please refer to this PR.

Working with RuboCop

Configuring RuboCop

As mentioned earlier, the behaviour of RuboCop is controlled via the .rubocop.yml configuration file. This makes it possible to turn certain checks on/off. All configurations in this file are inherited from RuboCop default configuration.

The command rubocop --auto-gen-config generated an additional .rubocop_todo.yml file. This file is specifically helpful for existing projects. On executing rubocop on your existing projects, the .rubocop_todo.yml file records all the offences from your codebase. You can address the issues gradually as you work on that code, making it easy for developers to go step by step.

An example .rubocop_todo.yml file might look as below:

# Offense count: 2
# Configuration parameters: EnforcedStyle, Include.
# SupportedStyles: Gemfile, gems.rb
# Include: **/Gemfile, **/gems.rb, **/Gemfile.lock, **/gems.locked
Bundler/GemFilename:
  Exclude:
    - 'app/controllers/dashboard_controller.rb'
    - 'Gemfile'

The .rubocop_todo.yml identified the files' issues and added them to the Exclude list. The next time you run rubocop, it will run on all the files, excluding the abovementioned list.

This is possible because the .rubocop.yml inherits these changes from the .rubocop_todo.yml file.

An example .rubocop.yml will look as below:

inherit_from: .rubocop_todo.yml

inherit_mode:
  merge:
    - Exclude

....
....

Note:

The added rubocop todo file does not mean that the offences have been solved; it simply indicates that you have repeatedly suppressed the warnings you received It would help if you fixed them one by one.

Automatically correcting offenses

The rubocop command, when successfully executed, will show you the number of offences that can be autocorrected.

$ rubocop
Inspecting 264 files
....................C..............CCC..............
......................
264 files inspected, 182 offenses detected, 86 offenses autocorrectable

As seen above, 86 offenses are autocorrectable. You must pass the -a option to the rubocop command to autocorrect these issues.

rubocop -a

To save time on repetitive code formatting fixes, some use auto-correction. However, double-checking changes prevents potential errors before committing.

Set your own RuboCop rules

Rubocop defaults to the Ruby standard style guide, which you and your teams may want to diverge from.

For example, the maximum number of lines a method can have is set to 10 as the default value by RuboCop. You can override this value by adding the below lines to your .rubocop_todo.yml file.

Metrics/MethodLength:
  Max: 5

You can also altogether turn off a rule. To disable the Style/DateTime: check, you must set the Enabled key to false.

Style/DateTime:
  Enabled: false

Integration with CI

Integrating RuboCop with your CI pipeline offers several advantages:

  • Automated Code Reviews:

    RuboCop automates the code review process by analyzing your codebase for style violations, potential issues, and adherence to best practices. By integrating RuboCop with CI, you can ensure that every code change is automatically checked against your defined coding standards.

  • Immediate Feedback:

    CI systems provide immediate feedback on code changes, allowing developers to catch and address issues early in the development cycle. Integrating RuboCop with CI ensures that style violations are identified and addressed before merging the code into the main branch.

  • Consistency:

    CI ensures that all code changes are subjected to the same rules and standards, promoting consistency across your codebase. By enforcing consistent coding styles and practices, RuboCop helps maintain a high code quality and readability level.

Integrate RuboCop into your CI pipeline by adding it to your CI configuration file (e.g., .gitlab-ci.yml, .travis.yml, or .github/workflows/main.yml). Here's an example configuration for GitLab CI:

# .gitlab-ci.yml
stages:
  - lint

rubocop:
  stage: lint
  image: ruby:latest
  script:
    - gem install rubocop
    - rubocop

Benefits of RuboCop in Rails Development

  • Consistency:

    Consistency is critical to writing maintainable code. RuboCop enforces consistent coding styles and practices across your codebase, ensuring all developers adhere to the same standards. This consistency makes it easier for team members to understand and collaborate on the code.

  • Code Quality:

    By flagging potential issues and style violations, RuboCop helps maintain code quality. It identifies common pitfalls, such as unused variables, redundant code, or inefficient constructs, allowing you to address them early in development.

  • Productivity:

    RuboCop automates the code review process by providing instant feedback on your code changes. This reduces the time spent on manual code reviews and allows developers to focus more on writing code rather than nitpicking style issues.

  • Learning Tool:

    RuboCop is an educational tool for developers, helping them learn and internalize best practices and coding conventions. Developers can improve their Ruby coding skills by reviewing RuboCop's suggestions and explanations.

Closing Remark

Could your team use some help with topics like this and others covered by ShakaCode's blog and open source? We specialize in optimizing Rails applications, especially those with advanced JavaScript frontends, like React. We can also help you optimize your CI processes with lower costs and faster, more reliable tests. Scraping web data and lowering infrastructure costs are two other areas of specialization. Feel free to reach out to ShakaCode's CEO, Justin Gordon, at [email protected] or schedule an appointment to discuss how ShakaCode can help your project!
Are you looking for a software development partner who can
develop modern, high-performance web apps and sites?
See what we've doneArrow right