RuboCop Commands & Style Enforcement Guide

· Ruby on Rails · By Zeeshan Ahmad

Commonly Used RuboCop Commands

1. bin/rubocop

Runs RuboCop on the entire project and checks for code style violations without making changes.

Use: To identify issues in your code before making any changes.

2. bin/rubocop -f

Runs RuboCop and specifies the output format.

  • simple: A concise summary of offenses.
  • offenses: Detailed output of offenses (default).
  • json: Useful for tool integrations.

Example:

bash
bin/rubocop -f simple

3. bin/rubocop -a

Automatically fixes issues in the code wherever possible.

Note: Not all issues can be auto-corrected.

4. bin/rubocop -a --only Style/StringLiterals

Runs auto-correction for a specific cop or rule.

Example:

bash
bin/rubocop -a --only Style/StringLiterals

5. bin/rubocop -f simple

Outputs a simplified report summarizing the offenses.

Use: For a quick overview of violations.

6. bin/rubocop --auto-gen-config

Generates a .rubocop_todo.yml file to suppress current offenses.

Use: To start RuboCop on a legacy codebase and prioritize future compliance.

Example Flow:

bash
bin/rubocop --auto-gen-config
# Update .rubocop.yml
inherit_from:
  - .rubocop_todo.yml

Additional Commands

bin/rubocop --only <cop_name>

Checks for offenses related to a specific cop.

Example:

bash
bin/rubocop --only Metrics/MethodLength

bin/rubocop --fail-level <severity>

Sets the failure threshold based on severity.

Example:

bash
bin/rubocop --fail-level error

bin/rubocop --display-cop-names

Displays the names of cops that detect issues.

bin/rubocop --out <file>

Outputs the results to a file.

Example:

bash
bin/rubocop --format json --out rubocop.json

bin/rubocop --rails

Enables Rails-specific cops for checking conventions and best practices.

Conclusion

Using these RuboCop commands, you can efficiently maintain code quality in Ruby and Rails projects. Combine these with your CI workflow to automate style and quality checks.

Home · All Tools · Blog