LoginSignup
570

More than 5 years have passed since last update.

Rubocopを使ってコーディングルールへの準拠チェックを自動化

Last updated at Posted at 2013-08-07

はじめに

チーム内でコーディング規約を作っても,ついクセで違う書き方をしたり気にしない人がいたりして形骸化しがちだと思います.またレビュー時に細かい違いを指摘するのも面倒です.そんなときはrubocopを入れましょう

インストール

gem i rubocop

これでrubocopコマンドがインストールされ,rubocop foo.rbとするとチェックできます.
コマンドラインからいちいち実行したくないので,各エディタのプラグインをインストール.すると,以下のようにコーディングルールに合わない箇所を指摘してくれます.

kobito.1375877325.003516.png

ここでは「bodyが1行のときは後置ifか,&&や||を使え」と言われています.

設定

rubocopが準拠するコーディング規約は同じ開発者が提案しているものですが,.rubocop.ymlファイルを編集することで自分達に合った形に変更することができます.
うちではチームで話し合い,10箇所ぐらい変更しました.

うちの設定

こんな感じです.(rubocop v0.9.1)
最近のバージョンだとデフォルト設定は別ファイルに切り出されたのでカスタマイズしやすい.

.rubocop.yml
# This file overrides https://github.com/bbatsov/rubocop/blob/master/config/default.yml

# Use UTF-8 as the source file encoding.
Encoding:
  Enabled: false

# Limit lines to 80 characters.
LineLength:
  Enabled: false

# Avoid methods longer than 10 lines of code
MethodLength:
  Enabled: false

# Favor modifier if/unless usage when you have a single-line body.
IfUnlessModifier:
  Enabled: false

# Favor modifier while/until usage when you have a single-line body.
WhileUntilModifier:
  Enabled: false

# Preferred collection methods.
CollectionMethods:
  Enabled: false

# Avoid Perl-style regex back references.
AvoidPerlBackrefs:
  Enabled: false

# Don't interpolate global, instance and class variables directly in strings.
VariableInterpolation:
  Enabled: false

# Don't use semicolons to terminate expressions.
Semicolon:
  AllowBeforeEndInOneLineMethods: false

# Use only ascii symbols in comments.
AsciiComments:
  Enabled: false

# TODO: Change it to true when $redis and $mixpanel is removed
#
# Do not introduce global variables.
AvoidGlobalVars:
  Enabled: false

関連

obective-cならObjective-C - 意識の高さからかコードフォーマッター設定を公開 - Qiita

vimから自動実行するなら Ruby - Rubocopをsyntastic.vimから実行する - Qiita

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
570