Install and use Rubocop - TLDR
Resources:
1. Installation
# Gemfile
group :development, :test do
gem 'rubocop-rails', require: false
end
# console
bundle
echo > .rubocop.yml
# .rubocop.yml - basic setup example
require:
- rubocop-rails
AllCops:
NewCops: enable
TargetRubyVersion: 3.1.2
Exclude:
- vendor/bundle/**/*
- '**/db/schema.rb'
- '**/db/**/*'
- 'config/**/*'
- 'bin/*'
- 'config.ru'
- 'Rakefile'
Style/Documentation:
Enabled: false
Style/ClassAndModuleChildren:
Enabled: false
Rails/Output:
Enabled: false
Style/EmptyMethod:
Enabled: false
Bundler/OrderedGems:
Enabled: false
Lint/UnusedMethodArgument:
Enabled: false
Style/FrozenStringLiteralComment:
Enabled: false
2. Run the cops
# console - run check:
bundle exec rubocop
# console - run check on specific file/folder:
rubocop app/models/user.rb
3. Disable cops
- in a file, for a method:
app/models/user.rb
# rubocop: disable Metrics/AbcSize, Metrics/MethodLength
def full_name
...
end
# rubocop: enable Metrics/AbcSize, Metrics/MethodLength
- on a whole file:
# .rubocop.yml
Metrics/ClassLength:
Exclude:
- 'app/models/user.rb'
- 'app/controllers/users_controller.rb'
4. AutoCorrect
# console - safe auto correct
rubocop -a
# console - dangerous auto correct
rubocop - A
# console - autocorrect a single specific cop
bundle exec rubocop -a --only Style/FrozenStringLiteralComment
bundle exec rubocop -A --only Layout/EmptyLineAfterMagicComment
# generate comments for uncorrected problems and stop flagging them as TODO:
rubocop --auto-correct --disable-uncorrectable
5. Github workflows
# mkdir .github
# mkdir .github/workflows
# echo > .github/workflows/.lint.yml
name: Code style
on: [pull_request]
jobs:
lint:
name: all linters
runs-on: ubuntu-latest
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v3
- uses: ruby/setup-ruby@v1
with:
bundler-cache: true
- name: rubocop
run: bundle exec rubocop --parallel
# - name: erb-lint
# run: bundle exec erblint --lint-all
That’s it!