什么是RuboCop
Rubocop 是基于 ruby-style-guide / Ruby 风格指导 实现的一个代码风格检查器。
如何安装
$ gem install rubocop
或使用bundle
安装
gem 'rubocop', require: false
如何使用
$ rubocop
或指定目录或文件
$ rubocop app spec lib/tasks/something.rb
$ rubocop app/models/user.rb
app/models/user.rb:364:25: C: Prefer single-quoted strings when you don't need string interpolation or special symbols.
description: a1["description"]
^^^^^^^^^^^^^
app/models/user.rb:367:29: C: Space missing after comma.
items = items.sort { |a1,a2| a2[:watchers] <=> a1[:watchers] }.take(14)
^
app/models/user.rb:368:81: C: Line is too long. [85/80]
Rails.cache.write(user.github_repositories_cache_key, items, expires_in: 15.days)
^^^^^
app/models/user.rb:371:3: C: Use only ascii symbols in comments.
# 重新生成 Private Token
^^^^^^^^^^^^^^^^^^^^
1 file inspected, 181 offenses detected
竟然有181个地方需要修改!
先自动化修复一部分
$ rubocop -a app/models/user.rb
1 file inspected, 206 offenses detected, 149 offenses corrected
跑测试确认一下
rspec spec/models/user_spec.rb
✌️,继续修改
app/models/user.rb:368:81: C: Line is too long. [85/80]
Rails.cache.write(user.github_repositories_cache_key, items, expires_in: 15.days)
^^^^^
app/models/user.rb:371:3: C: Use only ascii symbols in comments.
# 重新生成 Private Token
^^^^^^^^^^^^^^^^^^^^
又是警告, 但我想写中文注释,一行80个字太短了,我们加一下配置。
.rubocop.yml
AllCops:
RunRailsCops: true
Include:
- '**/Gemfile'
- '**/Rakefile'
Exclude:
- 'bin/*'
- 'db/migrate/*'
- 'db/seeds.rb'
- 'db/schema.rb'
- 'vendor/bundle/**/*'
Metrics/LineLength:
Max: 120
Style/AsciiComments:
Enabled: false
再看一下
$ rubocop app/model/user.rb
app/models/user.rb:343:3: C: Assignment Branch Condition size for fetch_github_repositories is too high. [29.9/15]
def self.fetch_github_repositories(user_id)
^^^
app/models/user.rb:343:3: C: Method has too many lines. [23/10]
def self.fetch_github_repositories(user_id)
^^^
1 file inspected, 23 offenses detected
这样, 要修复的就少多了。
网友评论