LoginSignup
4
9

More than 3 years have passed since last update.

rubocopの導入[初心者向け]

Last updated at Posted at 2020-05-16

はじめに

rubocopとは簡潔にいうとコーディング規約をチェックしてくれるgemです。
参考記事: rubocopとは

導入のプロセスなどもできるだけ詳しく記述したので最後までご覧いただけましたら幸いです。
説明はいいから導入だけしたいという方向けに初めに.rubocop.ymlファイルの最終形も記述しています。

対象読者

  • rubocopを導入したことがないがどのように導入したらいいかわからない方
  • 少しきれいなコードを書くことを意識してみたい方

環境

$ rails -v
Rails 6.0.2.2

$ ruby -v
ruby 2.7.0

手順

  1. Gemfileにrubocopを記述してbundle install
  2. rubocop.ymlファイルに何をチェックする、しないを記述する

1. Gemfileにrubocopを記述してbundle install

GemFileに記述します

group :development do
  gem 'rubocop', require: false
  gem 'rubocop-rails', require: false
end
$ bundle install

$ rubocop
The following cops were added to RuboCop, but are not configured. Please set Enabled to either `true` or `false` in your `.rubocop.yml` file:
 - Layout/EmptyLinesAroundAttributeAccessor (0.83)
 - Layout/SpaceAroundMethodCallOperator (0.82)
 - Lint/RaiseException (0.81)
:
48 files inspected, 223 offenses detected

ひとまず導入完了です。

2. rubocop.ymlファイルに何をチェックするかを記述する

48ファイル223箇所規約違反があると指摘されました。
これを全て修正するのは途方もない時間がかかる、、、ので
規約違反の内容を記述して通るようにしてくれるコマンドがあるのでそのコマンドを実行します。

$ bundle exec rubocop --auto-gen-config
# 規約違反が記録された.rubocop_todo.ymlファイルが作成される
rubocop.yml
inherit_from: .rubocop_todo.yml #上記コマンドで自動で記述される
rubocop_todo.yml
# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2020-05-16 08:08:30 +0900 using RuboCop version 0.83.0.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.

# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: TreatCommentsAsGroupSeparators, Include.
# Include: **/*.gemfile, **/Gemfile, **/gems.rb
Bundler/OrderedGems:
  Exclude:
    - 'Gemfile'

# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, IndentationWidth.
# SupportedStyles: with_first_argument, with_fixed_indentation
Layout/ArgumentAlignment:
  Exclude:
    - 'bin/webpack'
    - 'bin/webpack-dev-server'






# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: MinSize.
# SupportedStyles: percent, brackets
Style/SymbolArray:
  EnforcedStyle: brackets

# Offense count: 45
# Cop supports --auto-correct.
# Configuration parameters: AutoCorrect, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns.
# URISchemes: http, https
Layout/LineLength:
  Max: 198

規約違反箇所が通るように自動でファイルが作成されたので再度rubocopを実行してみます。

$ rubocop
The following cops were added to RuboCop, but are not configured. Please set Enabled to either `true` or `false` in your `.rubocop.yml` file:
 - Layout/EmptyLinesAroundAttributeAccessor (0.83)
 - Layout/SpaceAroundMethodCallOperator (0.82)
 - Lint/RaiseException (0.81)
 - Lint/StructNewOverride (0.81)
 - Style/ExponentialNotation (0.82)
 - Style/HashEachMethods (0.80)
 - Style/HashTransformKeys (0.80)
 - Style/HashTransformValues (0.80)
 - Style/SlicingWithRange (0.83)
For more information: https://docs.rubocop.org/en/latest/versioning/
Inspecting 48 files
................................................

48 files inspected, no offenses detected

規約違反なし!(当たり前、、、)

rubocop_todo.ymlに規約違反の箇所が通るように記述されているので
最終的にrubocop_todo.ymlが空になるようにしていきます!

まず、自動生成されたファイルはrubocopのチェックの対象外にしたいと思うのでrubocop.ymlファイルを修正していきます。

rubocop.yml
# 自動生成されたファイルを対象外にする
AllCops:
  Exclude:
    - 'Gemfile'
    - 'node_modules/**/*'
    - 'bin/*'
    - 'db/**/*'
    - 'config/**/*'
    - 'test/**/*'
    - 'spec/**/*'
$ rubocop
The following cops were added to RuboCop, but are not configured. Please set Enabled to either `true` or `false` in your `.rubocop.yml` file:
 - Layout/EmptyLinesAroundAttributeAccessor (0.83)
 - Layout/SpaceAroundMethodCallOperator (0.82)
 - Lint/RaiseException (0.81)
 - Lint/StructNewOverride (0.81)
 - Style/ExponentialNotation (0.82)
 - Style/HashEachMethods (0.80)
 - Style/HashTransformKeys (0.80)
 - Style/HashTransformValues (0.80)
 - Style/SlicingWithRange (0.83)
For more information: https://docs.rubocop.org/en/latest/versioning/
Inspecting 12 files
............

12 files inspected, no offenses detected

チェックするファイルが12個に減りました。
この量ならおそらく自分でチェックできると思うので.rubocop_todo.ymlファイルと下記のコードを削除します。

rubocop.yml
inherit_from: .rubocop_todo.yml # 削除
$ rubocop

Offenses:

Rakefile:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
# Add your own tasks in files placed in lib/tasks ending in .rake,
^
Rakefile:2:81: C: Layout/LineLength: Line is too long. [90/80]
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
                                                                                ^^^^^^^^^^
app/channels/application_cable/channel.rb:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
module ApplicationCable
^
app/channels/application_cable/connection.rb:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
module ApplicationCable
^
app/controllers/application_controller.rb:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
class ApplicationController < ActionController::Base
^
app/helpers/application_helper.rb:1:1: C: Style/Documentation: Missing top-level module documentation comment.
module ApplicationHelper
^^^^^^
app/helpers/application_helper.rb:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
module ApplicationHelper
^
app/jobs/application_job.rb:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
class ApplicationJob < ActiveJob::Base
^
app/jobs/application_job.rb:5:81: C: Layout/LineLength: Line is too long. [82/80]
  # Most jobs are safe to ignore if the underlying records are no longer available
                                                                                ^^
app/mailers/application_mailer.rb:1:1: C: Style/Documentation: Missing top-level class documentation comment.
class ApplicationMailer < ActionMailer::Base
^^^^^
app/mailers/application_mailer.rb:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
class ApplicationMailer < ActionMailer::Base
^
app/models/application_record.rb:1:1: C: Style/Documentation: Missing top-level class documentation comment.
class ApplicationRecord < ActiveRecord::Base
^^^^^
app/models/application_record.rb:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
class ApplicationRecord < ActiveRecord::Base
^
app/models/like.rb:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
class Like < ApplicationRecord
^
app/models/post.rb:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
class Post < ApplicationRecord
^
app/models/user.rb:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
class User < ApplicationRecord
^
config.ru:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
# This file is used by Rack-based servers to start the application.
^

12 files inspected, 17 offenses detected

17箇所規約違反していますがよく見ると似たような規約違反(下記)が存在するのでこの警告は回避します。(警告の詳細はこの記事では省略します)

Style/FrozenStringLiteralComment: Missing frozen string literal comment.
rubocop.yml
# 以下を追記
Style/FrozenStringLiteralComment:
  Enabled: false
$ rubocop
Offenses:

Rakefile:2:81: C: Layout/LineLength: Line is too long. [90/80]
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
                                                                                ^^^^^^^^^^
app/helpers/application_helper.rb:1:1: C: Style/Documentation: Missing top-level module documentation comment.
module ApplicationHelper
^^^^^^
app/jobs/application_job.rb:5:81: C: Layout/LineLength: Line is too long. [82/80]
  # Most jobs are safe to ignore if the underlying records are no longer available
                                                                                ^^
app/mailers/application_mailer.rb:1:1: C: Style/Documentation: Missing top-level class documentation comment.
class ApplicationMailer < ActionMailer::Base
^^^^^
app/models/application_record.rb:1:1: C: Style/Documentation: Missing top-level class documentation comment.
class ApplicationRecord < ActiveRecord::Base
^^^^^

12 files inspected, 5 offenses detected

5箇所まで減りました。

Layout/LineLength: Line is too long. [90/80]

これは1行あたりの文字数がで80文字という規約です。
80文字は厳しいので150文字にしたいと思います。

rubocop.yml
# 1行の最大文字数を150字にする
LineLength:
  Max: 150
$ rubocop

Offenses:

app/helpers/application_helper.rb:1:1: C: Style/Documentation: Missing top-level module documentation comment.
module ApplicationHelper
^^^^^^
app/mailers/application_mailer.rb:1:1: C: Style/Documentation: Missing top-level class documentation comment.
class ApplicationMailer < ActionMailer::Base
^^^^^
app/models/application_record.rb:1:1: C: Style/Documentation: Missing top-level class documentation comment.
class ApplicationRecord < ActiveRecord::Base
^^^^^

12 files inspected, 3 offenses detected

残り3箇所。ラストスパート!

Style/Documentation: Missing top-level module documentation comment.

これはクラスやモジュールを書くまえにドキュメントがないという指摘です。
クラスやモジュールの前にドキュメントを書けばいいのですが今回は回避します。

rubocop.yml
# ドキュメントのないclass, moduleを許可する
Style/Documentation:
  Enabled: false
$ rubocop
The following cops were added to RuboCop, but are not configured. Please set Enabled to either `true` or `false` in your `.rubocop.yml` file:
 - Layout/EmptyLinesAroundAttributeAccessor (0.83)
 - Layout/SpaceAroundMethodCallOperator (0.82)
 - Lint/RaiseException (0.81)
 - Lint/StructNewOverride (0.81)
 - Style/ExponentialNotation (0.82)
 - Style/HashEachMethods (0.80)
 - Style/HashTransformKeys (0.80)
 - Style/HashTransformValues (0.80)
 - Style/SlicingWithRange (0.83)
For more information: https://docs.rubocop.org/en/latest/versioning/
Inspecting 12 files
............

12 files inspected, no offenses detected

無事に指摘箇所の修正は終わりました。

The following cops were added to RuboCop, but are not configured. Please set Enabled to either `true` or `false` in your `.rubocop.yml` file:

最後にrubocop.ymlにtrueかfalseを書いてとあるので記述します。

$ rubocop

Inspecting 12 files
............

12 files inspected, no offenses detected

きれいになりました!!

完成形

rubocop.yml
# 自動生成したファイルはRubocopでチェックしない
AllCops:
  Exclude:
    - 'Gemfile'
    - 'node_modules/**/*'
    - 'bin/*'
    - 'db/**/*'
    - 'config/**/*'
    - 'test/**/*'
    - 'spec/**/*'

Style/FrozenStringLiteralComment:
  Enabled: false

# 1行の最大文字数を150字にする
LineLength:
  Max: 150

# ドキュメントのないclassを許可する
Style/Documentation:
  Enabled: false

# rubocopをかけたときに警告が出たのでtrue or falseの選択
Layout/EmptyLinesAroundAttributeAccessor:
  Enabled: true

Layout/SpaceAroundMethodCallOperator:
  Enabled: true

Lint/RaiseException:
  Enabled: true

Lint/StructNewOverride:
  Enabled: true

Style/ExponentialNotation:
  Enabled: true

Style/HashEachMethods:
  Enabled: true

Style/HashTransformKeys:
  Enabled: true

Style/HashTransformValues:
  Enabled: true

Style/SlicingWithRange:
  Enabled: true

おわりに

rubocopを導入するときれいなコードを書くという意識が生まれるのでぜひ導入してみてください。
最後までご覧いただきありがとうございます。

4
9
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
4
9