Rubocop is a Ruby static code analysis tool. ruby-style-guide will point out the corrections and improvements in the source code.
Indentation deviations, unnecessary spaces, line breaks, etc. are automatically corrected by typing a specific command, so you can format the code so that it is easy for you to read as well as for others. can.
gemfile
gem 'rubocop', require: false
Terminal
bundle install
Terminal
bundle exec rubocop
When run, you will get output similar to the following:
These are the fixes detected by Rubocop. However, if you follow all the default rules, you'll have too much to worry about when writing code, so you can set the rules you and your team allow.
In the application directory Create a file called .rubocop.yml and write the settings in it.
.rubocop.yml
AllCops:
#Set directories to exclude. For example, schema and migration files are rarely rewritten, so they are not detected.
Exclude:
- bin/*
- db/schema.rb
- node_modules/**/*
- db/migrate/*
- vendor/**/*
#Check for Rails
Rails:
enabled: true
# "Missing top-level class documentation comment."Disable
Style/Documentation:
Enabled: false
# "Prefer single-quoted strings when you don't need string interpolation or special symbols."Disable
Style/StringLiterals:
Enabled: false
# "Line is too long"Disable
Metrics/LineLength:
Enabled: false
#'frozen_string_literal: true'Disable
Style/FrozenStringLiteralComment:
Enabled: false
Various settings such as are possible. I will play around with it by referring to Default settings.
After setting, again
Terminal
bundle exec rubocop
Then, you can see that 72files is 56files, which is less than before.
Terminal
bundle exec rubocop --auto-gen-config
A file called .rubocop.todo.yml is automatically generated. As a result, all corrections will be temporarily invalidated. If you run rubocop here, there will be no corrections.
ruby:.rubocop.todo.yml
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: TreatCommentsAsGroupSeparators, ConsiderPunctuation, Include.
# Include: **/*.gemfile, **/Gemfile, **/gems.rb
Bundler/OrderedGems:
Exclude:
- 'Gemfile'
As an example, there is the above description. If you delete this description, the invalidated corrections of the relevant part will be restored. I will fix it immediately, but
Cop supports --auto-correct.
If there is a description, Rubocop will automatically correct it with the following command.
#### **`Terminal`**
```python
bundle exec rubocop -a
This time, the gem description in the Gemfile is not in alphabetical order, but it is rearranged in the correct order.
`bundle exec rubocop --auto-gen-config``` and Generate
`.rubocop.todo.yml```. .rubocop.todo.yml
Repeat 4.3.In the actual field, it is automated and it seems that you will not fix it yourself, I'm still a beginner, so I'll improve each one and check the rules. I try to be an engineer who can write easy-to-read code from the beginning.
Recommended Posts