一个Ruby静态代码分析器:rubocop
jopen
10年前
这是一个Ruby静态代码分析器,基于社区Ruby编码风格指南Ruby Style Guide。除了报告代码中的问题,RuboCop还可以自动为你修复一些问题。
安装
RuboCop的安装是非常标准:
$ gem install rubocop
If you'd rather install RuboCop usingbundler, don't require it in yourGemfile:
gem 'rubocop', require: false
基本用法
不带参数运行rubocop会检查当前目录下的所有Ruby源文件:
$ rubocop
另外,您可以通过rubocop指定文件和目录进行检查:
$ rubocop app spec lib/something.rb
Here's RuboCop in action. Consider the following Ruby source code:
def badName if something test end end
Running RuboCop on it (assuming it's in a file namedtest.rb) would produce the following report:
Inspecting 1 file W Offenses: test.rb:1:5: C: Use snake_case for method names. def badName ^^^^^^^ test.rb:2:3: C: Use a guard clause instead of wrapping the code inside a conditional expression. if something ^^ test.rb:2:3: C: Favor modifier if usage when having a single-line body. Another good alternative is the usage of control flow &&/||. if something ^^ test.rb:4:5: W: end at 4, 4 is not aligned with if at 2, 2 end ^^^ 1 file inspected, 4 offenses detected
For more details check the available command-line options:
$ rubocop -h
Command flag | Description |
---|---|
-v/--version | Displays the current version and exits. |
-V/--verbose-version | Displays the current version plus the version of Parser and Ruby. |
-F/--fail-fast | Inspects in modification time order and stops after first file with offenses. |
-d/--debug | Displays some extra debug output. |
-D/--display-cop-names | Displays cop names in offense messages. |
-c/--config | Run with specified config file. |
-f/--format | Choose a formatter. |
-o/--out | Write output to a file instead of STDOUT. |
-r/--require | Require Ruby file (see Loading Extensions). |
-R/--rails | Run extra Rails cops. |
-l/--lint | Run only lint cops. |
-a/--auto-correct | Auto-correct certain offenses. Note: Experimental - use with caution. |
--only | Run only the specified cop(s) and/or cops in the specified departments. |
--except | Run all cops enabled by configuration except the specified cop(s) and/or departments. |
--auto-gen-config | Generate a configuration file acting as a TODO list. |
--show-cops | Shows available cops and their configuration. |
--fail-level | Minimum severity for exit with error code. Full severity name or upper case initial can be given. Normally, auto-corrected offenses are ignored. UseAorautocorrectif you'd like them to trigger failure. |