Leon's Blogging

Coding blogging for hackers.

用 Rubocop 寫出好風格 (Ruby & Rails Style Guide)

| Comments

rubocop 像是一個程式評量工具,會告知在 rails 中的寫法,要如何才會比較好!

1
gem install rubocop

指令

1
rubocop app spec lib/something.rb

自訂檔案

.rubocop.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# This is the configuration used to check the rubocop source code.

inherit_from: .rubocop_todo.yml

AllCops:
  Include:
    - '**/Rakefile'
    - '**/config.ru'
  Exclude:
    - 'db/**/*'
    - 'config/**/*'
    - 'script/**/*'
  TargetRubyVersion: 2.0

Style/Encoding:
  EnforcedStyle: always
  Enabled: true

Style/FrozenStringLiteralComment:
  EnforcedStyle: always

可以參考這份文件 config 將需要啟用的打開,不需要的關閉

產生檢測後的文件

rubocop --auto-gen-config 產生 .rubocop_todo.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2016-09-07 17:08:09 +0300 using RuboCop version 0.42.0.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.

# Offense count: 75
Metrics/AbcSize:
  Max: 19

# Offense count: 32
# Configuration parameters: CountComments.
Metrics/ClassLength:
  Max: 168

# Offense count: 28
Metrics/CyclomaticComplexity:
  Max: 7

# Offense count: 143
# Configuration parameters: CountComments.
Metrics/MethodLength:
  Max: 14

# Offense count: 11
# Configuration parameters: CountComments.
Metrics/ModuleLength:
  Max: 156

官方文件:

參考文件:

Comments