Skip to content

Instantly share code, notes, and snippets.

@jagdeepsingh
Last active June 7, 2018 06:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jagdeepsingh/049ad7a8fd7f6367086f311bc5827696 to your computer and use it in GitHub Desktop.
Save jagdeepsingh/049ad7a8fd7f6367086f311bc5827696 to your computer and use it in GitHub Desktop.
rubocop

A Ruby static code analyzer, based on the community Ruby style guide.

Title Link
Github https://github.com/rubocop-hq/rubocop
Docs http://rubocop.readthedocs.io/en/latest/
Ruby Style Guide https://github.com/rubocop-hq/ruby-style-guide

Contents:

1 Install gem

Add to your Gemfile:

group :development do
  gem 'rubocop', '~> 0.57.1', require: false
end

Run bundle install.

2 Usage

In your project directory, run rubocop. It will scan all the files at current level and nested below it for any violations of style guide.

3 Configuration

Create a file .rubocop.yml at root of project directory.

3.1 Metrics

Metrics cops deal with properties of the source code that can be measured, such as class length, method length, etc.

To set maximum allowed length of a line of code to 70, you can do:

# .rubocop.yml
Metrics/LineLength:
  Max: 70

To skip one or more files from being checked by this cop, you can define Exclude:

Metrics/LineLength:
  Exclude:
    - 'path/to/file'
    - 'path/to/another/file'

3.2 General

To disable a cop completely i.e. for all the files, you can configure it at global level:

Bundler/OrderedGems:
  Enabled: false

To disable all cops for a set of files, do:

AllCops:
  Exclude:
    - 'path/to/file'
    - 'path/to/another/file'

3.3 Style

# .rubocop.yml
Style/RescueModifier:
  Enabled: false

Style/SignalException:
  EnforcedStyle: semantic

Style/FileName:
  Exclude:
    - 'path/to/file'
    - 'path/**/*.rb'

Style/Documentation:
  Exclude:
    - 'path/to/file'

Style/EachWithObject:
  Exclude:
    - 'path/to/file'

Style/MultilineBlockChain:
  Exclude:
    - 'path/to/file'

3.4 Lint

# .rubocop.yml
Lint/HandleExceptions:
  Exclude:
    - 'path/to/file'

4 Common offences

4.1 Style/FrozenStringLiteralComment

Style/FrozenStringLiteralComment: Missing magic comment # frozen_string_literal: true.

As per this, you need to add a comment # frozen_string_literal: true to every ruby file at the top. You can ask rubocop to do it for you by running:

$ rubocop --auto-correct --only FrozenStringLiteralComment
@jagdeepsingh
Copy link
Author

Images

Logo

rubo-logo-horizontal

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment