Ruby Logo

RuboCop & Code Quality

Automate style enforcement and code quality checks with RuboCop, custom cops, and CI integrations.

Home Ruby RuboCop & Code Quality

RuboCop & Code Quality Automation

RuboCop enforces the Ruby style guide and highlights risky patterns before they land in main. We run it locally via Bundler, hook it into CI, and rely on auto-correction for mechanical fixes so humans can focus on design.

Daily Workflow Commands

bundle exec rubocop # run all cops bundle exec rubocop app/ # scope to a directory bundle exec rubocop -A # safe + unsafe autocorrect (review diff!) bundle exec rubocop --auto-gen-config # generate .rubocop_todo.yml

Use `-a` for safe auto-corrects only; reserve `-A` for feature branches where you will inspect every change. When the CLI flags offenses, fix them instead of disabling cops unless you can articulate the trade-off.

Project Configuration (.rubocop.yml)

AllCops: TargetRubyVersion: 3.2 NewCops: enable Exclude: - 'db/schema.rb' - 'node_modules/**/*' Layout/LineLength: Max: 110 Metrics/MethodLength: Max: 20 Exclude: - 'app/controllers/**/*' Rails: Enabled: true Style/Documentation: Enabled: false # prefer YARD only on public APIs

Keep overrides narrow. When you need to silence a cop for a valid reason, comment why inside the YAML so future maintainers understand the context.

Customizing Cops Responsibly

Only disable cops inline when there is no stylistic alternative. Use `# rubocop:disable ...` and `# rubocop:enable ...` on the smallest block possible, followed by an explanation.

def upsert_progress!(attrs) Progress.upsert(attrs, unique_by: %i[user_id topic_id]) rescue ActiveRecord::RecordNotUnique => e Rails.logger.warn("Progress collision: \\#{e.message}") # rubocop:disable Style/RescueStandardError -- upstream gem raises StandardError retry # rubocop:enable Style/RescueStandardError end

CI & Pre-Commit Integration

Git hooks

Add `bundle exec rubocop` to your pre-commit hook (e.g., via Overcommit or lefthook) so style regressions never reach GitHub.

GitHub Actions

- name: RuboCop run: bundle exec rubocop --parallel

Use `--parallel` to speed up checks in CI. Fail fast when offenses appear; PR authors must fix rather than mute the warnings.

Playbook

  • Regenerate `.rubocop_todo.yml` sparingly and always trim it back in the same PR.
  • When new cops land, enable them with `NewCops: enable` and address violations sooner rather than later.
  • Surface style decisions in PR descriptions and capture them inside `AGENTS.md` so future contributors stay aligned.

Quick Navigation

Related Topics

Video Tutorial

Watch and learn rubocop & code quality

Pro Tip: After reading through the content above, watch this video to reinforce your understanding and see the concepts in action!