iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 16
1
自我挑戰組

Ruby on Rails 與它們相關的東西系列 第 16

Day16 - Ruby on Rails 中的風格管理套件 RuboCop

  • 分享至 

  • twitterImage
  •  

前言

多人協作時,通常會規範 style,像是統一使用單引號、雙引號、每個方法最多不能超過幾行、每行的長度限制等
這時就需要透過 RuboCop 來進行把關

後續的文章會以此 repo 作為範例


Rubocop

Role models are important.
-- Officer Alex J. Murphy / RoboCop

進入官方網站便能看到這段話,由此可見風格規範的重要性

如何安裝

如文件所說直接在終端機輸入

gem install rubocop

接著放在 development 中,test 和 production 不需使用
或不放 Gemfile 中,只針對 CI 處理即可

可參考此 commit

# Gemfile 檔案

gem 'rubocop', '~> 0.90.0'

如何執行

在專案目錄下的終端機輸入

# 檢查全部的檔案
rubocop

# 只針對特定檔案、資料夾檢查
rubocop path/to/file path/to/directory

# 範例
rubocop app/controllers/application_controller.rb

備註: 善用 tldr 可看下 rubocop 怎麼使用

如何客製化 RuboCop 設定

可參考 Cop Documentation Style
裡面有提供各種範例的設定,可針對專案需求進行調整,
並將設定檔寫在 .rubocop.yml 中,可參考此 commit

# This is the configuration used to check the rubocop source code.
# url: https://docs.rubocop.org/rubocop/0.85/cops_style.html

AllCops:
  Exclude:
    - 'config/routes.rb'
    - 'db/schema.rb'
  TargetRubyVersion: 2.7.1
  TargetRailsVersion: 6.0.3.3

  Rails:
    Enabled: true

  Rails/UnknownEnv:
    Environments:
      - production
      - staging
      - development
      - test

# modern editors and terminal fit more than 120 characters.
Metrics/LineLength:
  Max: 120

# Class length is not critical to code quality
Metrics/ClassLength:
  Enabled: false

# Module length is not critical to code quality
Metrics/ModuleLength:
  Enabled: false

# Block length is ok to be long in DSLs like 'rspec' or 'rake'
Metrics/BlockLength:
  Enabled: false

# defualt '10 line' is too strict to us, and may clutter the class
Metrics/MethodLength:
  Max: 25

Metrics/AbcSize:
  Max: 25

# Most Rails generated class are not doced, and not needed
Style/Documentation:
  Enabled: false

# 'return' makes code more readable in some cases
Style/RedundantReturn:
  Enabled: false

Style/AsciiComments:
  Enabled: false

# Guard is not always good to readablity
# Note: It does not mean we don't use guard to reduce block levels
# In short methods, using guard is not necessary, e.g.
#   def foo(x)   | def foo(x)
#     if xxx?(x) |   return unless xxx?(x)
#       bar(x)   |   bar(x)
#     end        | end
#   end          |
Style/GuardClause:
  Enabled: false

# The rule expects
#
#   if xxxxxx
#     a_very_long_method_or_somethings_like_that......
#   end
#
# to be
#
#   a_very_long_method_or_somethings_like_that...... if xxxxxx
#
# It is not good looking at all.
Style/IfUnlessModifier:
  Enabled: false

# # bad
# a = [1, 2,]
#
# # good
# a = [
#   1, 2,
#   3,
# ]
#
# # good
# a = [
#   1,
#   2,
# ]
Style/TrailingCommaInArrayLiteral:
  EnforcedStyleForMultiline: consistent_comma

# # good
# foo(
#   1,
#   2,
# )
Style/TrailingCommaInArguments:
  EnforcedStyleForMultiline: consistent_comma

# # good
# a = {
#   1,
#   2,
# }
Style/TrailingCommaInHashLiteral:
  EnforcedStyleForMultiline: consistent_comma

# good
# class Foo
#
#   def bar
#     ...
#   end
#
# end
#
# bad
# class Foo
#   def bar
#     ...
#   end
# end

Style/ClassAndModuleChildren:
  Enabled: false

# bad
# "No special symbols"
# "No string interpolation"
# "Just text"

# good
# 'No special symbols'
# 'No string interpolation'
# 'Just text'
# "Wait! What's #{this}!"
# Style/StringLiterals:
#   EnforcedStyle: single_quotes (default)

如何只針對修改的檔案進行檢查就好

改了好多檔案,逐步檢查好麻煩,有什麼方法可以只針對修改的檔案檢查就好?
在自己 Local branch 的終端機輸入以下

# 若有更好的設定方式,歡迎留言交流 :)

# 方法1
rubocop $(git diff master --name-only)

# 方法2
git diff-tree -r --no-commit-id --name-only head..origin/master | xargs rubocop

# 備註: xargs 是 Linux 指令

或不想每次發 Pull requests (簡稱: pr) 都檢查全部的檔案

只想針對修改的檔案進行檢查就好,可參考此 commit 或此 commit

只想針對修改的行數進行檢查就好,可參考此 pr

備註: 安裝「pronto-rubocop」時,應該會踩到安裝失敗的雷,有相依「thor」比較舊的版本,可參考上面 pr 的解決方式

# 若有更好的設定方式,歡迎留言交流 :)

# 以 Travis CI 為例
# .travis.yml
git fetch origin master && master_sha1="$(cut -c -40<<<"$(cat .git/FETCH_HEAD)")" && pronto run -c $master_sha1 --exit-code

# 欲使用 pronto 這指令,需安裝「pronto-rubocop」
# 有安裝「pronto-rubocop」的話,這段也能直接在終端機輸入

某些行數不想被檢查,可以跳過檢查嗎

基於某些原因,某些 code 不想被 RuboCop 檢查 (說白就是不想處理 XD

想跳過檢查的話,可參考此 commit

# 依照 RuboCop 提醒,後面 oo_xx 改成對應的內容

# rubocop:disable oo_xx
your code
# rubocop:enable oo_xx


# 範例

# rubocop:disable Style/TrailingCommaInHashLiteral
your code
# rubocop:enable Style/TrailingCommaInHashLiteral

VS code 套件

每次都要輸入 rubocop 才知道哪些要改,好麻煩,
有沒有視覺化的工具可以協助呢?

VS code 有套件推薦使用「ruby-rubocop」

套件名稱: ruby-rubocop

套件連結: https://marketplace.visualstudio.com/items?itemName=misogi.ruby-rubocop

VS code 示範畫面


參考

機器戰警 RuboCop

小結

RuboCop 真的是又愛又恨的套件,好處是讓大家風格一致,壞處是處理時挺花時間的,遇到不知怎解決的問題時,Goolge 會是你的好朋友,再不行就跳過檢查(誤


鐵人賽文章連結:https://ithelp.ithome.com.tw/articles/10240956
medium 文章連結:https://link.medium.com/fx6sSkzeW9
本文同步發布於 小菜的 Blog https://riverye.com/

備註:之後文章修改更新,以個人部落格為主


上一篇
Day15 - 如何看自己打出去的 request 完整資訊,以 PostBin 和 Webhook.site 為例
下一篇
Day17 - Ruby on Rails 中的 awesome_print 讓你的 console 更好閱讀
系列文
Ruby on Rails 與它們相關的東西31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言