sajad torkamani

Note: This is mostly a quick reference for myself. If you're new to Rubocop, check out their official docs.

What is Rubocop?

Rubocop is a linter and code formatter for Ruby.

Installation & Setup

Install core gem and friends

Add to Gemfile and run bundle .

group :development, :test do
  gem 'rubocop', '~> 1.1', require: false
  gem 'rubocop-rails', require: false
  gem 'rubocop-rspec', require: false
  # other gems
end

Create .rubocop.yml for configuration

rubocop --init

Add configuration in .rubocop.yml

This is an okayish config to get started with for a Rails & RSpec app:

require:
  - rubocop-rails
  - rubocop-rspec

AllCops:
  NewCops: enable

Layout/FirstHashElementIndentation:
  EnforcedStyle: consistent

Layout/HashAlignment:
  Enabled: false

Lint/BinaryOperatorWithIdenticalOperands:
  Exclude:
    - 'spec/**/*'

Metrics/AbcSize:
  Enabled: false

Metrics/CyclomaticComplexity:
  Enabled: false

Metrics/MethodLength:
  Enabled: false

Metrics/PerceivedComplexity:
  Enabled: false

Metrics/BlockLength:
  Enabled: false

Rails/Output:
  Exclude:
    - 'db/**/*'

RSpec/ExampleLength:
  Enabled: false

RSpec/MultipleExpectations:
  Enabled: false

Style/Documentation:
  Enabled: false

Adding Rubocop to an existing project

If you have an existing Rails project, I'd just run rubocop -F to stop on the first error each time and just work my way through the errors one by one. I'd also be pretty relaxed with .rubocop.yml rules initially and perhaps disable a bunch of rules and fix them at a later time. Fun times!

Usage

Run for all files in current directory

rubocop

Autocorrect offenses (safe)

rubocop -a

Autocorrect offenses (unsafe)

rubocop -A

Autocorrect only formatting issues

rubocop -x

Fail on first error

rubocop -F

References

Tagged: Rails