📚

Rubocop で特定の Cop のみを対象として実行する

2024/02/29に公開

例えば以下のようなコードを Rubocop で実行すると

# test.rb
for i in 1..20
  if i % 3 == 0 && i % 5
    puts "FizzBuzz"
  elsif i % 3 == 0
    puts "Fizz"
  elsif i % 5 == 0
    puts "Buzz"
  else
    puts i
  end
end

以下のような結果になります。

$ rubocop test.rb
Inspecting 1 file
C

Offenses:

test.rb:1:1: C: [Correctable] Style/For: Prefer each over for.
for i in 1..20 ...
^^^^^^^^^^^^^^
test.rb:1:1: C: [Correctable] Style/FrozenStringLiteralComment: Missing frozen string literal comment.
for i in 1..20
^
test.rb:2:6: C: [Correctable] Style/NumericPredicate: Use (i % 3).zero? instead of i % 3 == 0.
  if i % 3 == 0 && i % 5
     ^^^^^^^^^^
test.rb:3:10: C: [Correctable] Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols.
    puts "FizzBuzz"
         ^^^^^^^^^^
test.rb:4:9: C: [Correctable] Style/NumericPredicate: Use (i % 3).zero? instead of i % 3 == 0.
  elsif i % 3 == 0
        ^^^^^^^^^^
test.rb:5:10: C: [Correctable] Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols.
    puts "Fizz"
         ^^^^^^
test.rb:6:9: C: [Correctable] Style/NumericPredicate: Use (i % 5).zero? instead of i % 5 == 0.
  elsif i % 5 == 0
        ^^^^^^^^^^
test.rb:7:10: C: [Correctable] Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols.
    puts "Buzz"
         ^^^^^^

1 file inspected, 8 offenses detected, 8 offenses autocorrectable

このときに『特定の Cop のみを対象と実行したい』場合には --only オプションが利用できます。

$ rubocop test.rb --only Style/StringLiterals
Inspecting 1 file
C

Offenses:

test.rb:4:10: C: [Correctable] Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols.
    puts "FizzBuzz"
         ^^^^^^^^^^
test.rb:6:10: C: [Correctable] Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols.
    puts "Fizz"
         ^^^^^^
test.rb:8:10: C: [Correctable] Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols.
    puts "Buzz"
         ^^^^^^

1 file inspected, 3 offenses detected, 3 offenses autocorrectable

-a とも併用できるので特定の Cop のみ修正したい場合にも利用できます。

GitHubで編集を提案

Discussion