LoginSignup
0
0

More than 3 years have passed since last update.

【Rails】Rubocop-airbnbを使ってみた!

Last updated at Posted at 2020-12-03

Rubocopとは

コードがコーディング規約を守っているかを解析する静的コード解析ツールのことです。
Rubocopは詳細な設定をしなくてはなりませんがRubocop-airbnbはairbnbで使用されているRubocopの設定を使用することができます。

Rubocop-airbnbのインストール

Gemfileのdevelopmentグループに以下の記述をした後bundle installしてください。

Gemfile
group :development do

  gem 'rubocop-airbnb'
end

ファイルの作成

アプリケーションフォルダの下に.rubocop.ymlと.rubocop_airbnb.ymlを作成します。
ファイル名の最初に「.」がついているので間違えないように注意が必要です!

.rubocop.yml
inherit_from:
  - .rubocop_airbnb.yml

#ここにはrubocopでコード解析したくないファイルやフォルダを指定
AllCops:
  Exclude:
    - 'db/**/*'
    - 'bin/*'
    - 'config/environments/*'
    - 'config/application.rb'
    - 'config/initializers/*'
    - 'config/spring.rb'
    - 'lib/tasks/*'
    - 'vendor/**/*'
    - 'path/ruby'
.rubocop_airbnb.yml
require:
  - rubocop-airbnb

コードの解析

ターミナル
$bundle exec rubocop --require rubocop-airbnb

実行結果(例)
Offenses:の後には具体的なコーディング違反箇所が出力されます。
今回の例では38ファイルをチェックして298箇所のコーディング違反があったと教えてくれています。

Inspecting 38 files
CC.....CCC..W...WWW.CCC.CW.C.W.........C.CC.CC..CCC.CC.............CCCCCCCC..........

Offenses:

:
:

38 files inspected, 298 offenses detected

コードの自動修正

解析内容をもとに一つ一つ修正していくのはとてつもなく大変ですが-aオプションをつけることで自動で修正してくれます。

ターミナル
$ bundle exec rubocop --require rubocop-airbnb -a

実行結果
コーディング違反は検出されなかったという結果が帰ってきました。

Inspecting 38 files

:
:

38 files inspected, no offenses detected

※自動修正が安全ではない場合は修正から除外されるなど全部修正されるわけではありません。
また公式ドキュメントには-aオプションは実験的なものなので使用には注意が必要との記載があります。
公式ドキュメント:
https://docs.rubocop.org/rubocop/usage/auto_correct.html#safe-auto-correct

その他

ファイル単位やフォルダ単位での実行

$ bundle exec rubocop --require rubocop-airbnb -a {解析対象ファイルor解析対象フォルダ}

origin/masterとの差分があるファイルに対して実行

$ bundle exec rubocop --require rubocop-airbnb -a $(git diff $(git merge-base origin/master HEAD) --diff-filter=d --name-only)

最後に

ご覧いただきありがとうございました。
初心者のためご指摘等ございましたら教えていただけると幸いです。

0
0
0

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
0
0