ruby代码检查器rubocop

什么是RuboCop

Rubocop 是基于 ruby-style-guide / Ruby 风格指导 实现的一个静态代码分析工具。
使用rubocop有助于个人/团队写出风格统一的代码

如何安装

$ gem install rubocop

或使用bundle安装

gem 'rubocop', require: false

如何使用

$ rubocop

或指定目录或文件

$ rubocop app spec lib/tasks/something.rb

ruby-china为例

$ 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个地方需要修改!
其中有很多是 {:a => :b} 修改为 {a: :b}使用类似的问题
可以使用
rubocop自动化修复一部分, 加上-a`参数

$ 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配置。

.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

这样, 要修复的就少多了。

剩下的问题如Method has too many lines. [23/10]的警告就看你自己的想法了。
可以参考官方配置
.rubocop.yml里进行配置.

编辑器支持

vim, emacs, sublime, atom, rubymine全部支持
参考第三方支持

comments powered by Disqus