RuboCop

RuboCop is a Ruby code linter.

A quick-and-dirty starting config, bootstrapping a Rails app:

1
2
3
4
5
6
7
# Gemfile
group :development do
  gem "rubocop", require: false
  gem "rubocop-rails", require: false
  gem "rubocop-shopify", require: false
  gem "rubocop-rspec", require: false
end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# .rubocop.yml
inherit_gem:
  rubocop-shopify: rubocop.yml

require:
  - rubocop-rails
  - rubocop-rspec

AllCops:
  TargetRubyVersion: 2.7
  NewCops: enable
  Exclude:
    - 'tmp/**/*'
    - 'vendor/**/*'

Note that the rubocop-shopify dependency is purely a style choice (and my default preference), sticking with Rubocop’s baseline, or or use AirBNB’s plugin, or whatever. StandardRB is another option that likes to run its own binary, but can run through standard rubocop tooling with this config.

If you’re adding to an existing codebase, rubocop --auto-gen-config will scan your code and create a file of known violations to whitelist, which you can then incrementally remove and correct. This will require you update your .rubocop.yml to recognize it:

1
2
3
# .rubocop.yml, after inherit_gem and require sections:
inherit_from:
  - .rubocop_todo.yml

Class Structure

There’s a Layout/ClassStructure cop that allows you to specify a preferred ordering for certain parts of a class, for consistency. An example (source):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Layout/ClassStructure:
  ExpectedOrder:
    - module_inclusion
    - constants
    - association
    - public_attribute_macros
    - public_delegate
    - macros
    - initializer
    - public_class_methods
    - public_methods
    - protected_attribute_macros
    - protected_methods
    - private_attribute_macros
    - private_delegate
    - private_methods