[Rubocop] 特定のルールを特定のファイル(ディレクトリ)でのみ無効にする

概要

Rubocopにて、このファイル(ディレクトリ)ではあのルールは無効にしたいなと思って試してみたら普通に出来たので備忘録を残す。

そもそもRubocopってなんなのさという方は以下を参考に。
[Ruby] RuboCopをインストールしてvimで実用化するまで | qs Developers

前提

  • ruby 2.4.1
  • rubocop 0.52.1

方法

file_a.rb

class Hoge

end

file_b.rb

class Fuga

end

の2つのRubyスクリプトを用意する。両クラスとも、クラスの先頭に空行がある(というか空行しか無い)ので、そのままRubocopを実行すると両ファイルに対してLayout/EmptyLinesAroundClassBodyの警告が出る。

$ rubocop
Inspecting 2 files
CC

Offenses:

file_b.rb:2:1: C: Layout/EmptyLinesAroundClassBody: Extra empty line detected at class body beginning.
file_a.rb:2:1: C: Layout/EmptyLinesAroundClassBody: Extra empty line detected at class body beginning.

2 files inspected, 2 offenses detected

その際、例えばfile_a.rbは警告出していいけどfile_bでは出したくないという場合は、.rubocop.ymlに以下の記述を追加する。

Layout/EmptyLinesAroundClassBody:
  Exclude:
    - 'file_b.rb'

これでfile_a.rbにのみLayout/EmptyLinesAroundClassBodyが適用されるようになる。

$ rubocop
Inspecting 2 files
.C

Offenses:

file_a.rb:2:1: C: Layout/EmptyLinesAroundClassBody: Extra empty line detected at class body beginning.

2 files inspected, 1 offense detected

個別に実行しても同様。

$ rubocop file_a.rb
Inspecting 1 file
C

Offenses:

file_a.rb:2:1: C: Layout/EmptyLinesAroundClassBody: Extra empty line detected at class body beginning.

1 file inspected, 1 offense detected
$ rubocop file_b.rb
Inspecting 1 file
.

1 file inspected, no offenses detected

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です