Rails Tutorial を参考にしながら書いた下記のコードで RuboCop さんに指摘されたところに対処していきます。
指摘は2つ。
- Style/GuardClause: Use a guard clause instead of wrapping the code inside a conditional expression.
 - Layout/IndentationConsistency: Inconsistent indentation detected.
 
class StaticPagesController < ApplicationController
  before_action :logged_in_user, only: [:my_page]
  def home
    ...
  end
  def my_page
    ...
  end
  private
    # before action
    def logged_in_user
     unless user_signed_in?
       flash[:danger] = 'Please log in.'
       redirect_to root_url
     end
    end
end
Style/GuardClause: Use a guard clause instead of wrapping the code inside a conditional expression.
Offence の内容
app/controllers/static_pages_controller.rb:20:5: C: Style/GuardClause: Use a guard clause instead of wrapping the code inside a conditional expression.
    unless user_signed_in?
    ^^^^^^
参考: 
 ifとunlessの使い分け - Qiita
 ruby-style-guide/README.ja.md at japanese · fortissimo1997/ruby-style-guide
以下のような構成になっているのが良くない様子。
※追記:正常な状態と不正な状態の判定の順番の話かと思っていたのですが、その後調べるとどうやら1行で書くか否かとかそういう話の様子。理解が不十分なのであまりあてにならないです…
# before action
def logged_in_user
  unless user_signed_in?
    # 不正な状態(サインインしていない場合)の時の処理
    flash[:danger] = 'Please log in.'
    redirect_to root_url
  end
  # 正常な状態(サインイン済み)の時はここで抜ける
end
対処
以下のように書き換えるとOKになりました。
# before action
def logged_in_user
  return if user_signed_in? # 正常な状態(サインイン済み)ならここで抜ける
  # 不正な状態(サインインしていない場合)の時はこれ以降に進む
  flash[:danger] = 'Please log in.'
  redirect_to root_url
end
Layout/IndentationConsistency: Inconsistent indentation detected.
Offence の内容
app/controllers/static_pages_controller.rb:18:5: C: Layout/IndentationConsistency: Inconsistent indentation detected.
    def logged_in_user ...
    ^^^^^^^^^^^^^^^^^^
参考: 
 Class: RuboCop::Cop::Layout::IndentationConsistency — Documentation for rubocop (0.58.2)
 Rails enabled true and IndentationConsistency · Issue #3440 · rubocop-hq/rubocop
Rails tutorial 内でお勧めされている private 以下のインデントを一段深くする書き方がRuboCopに引っかかる。
対処
こちらはどうやらRailsとしてはこの書き方もありなようなので、RuboCopの設定を変更して、OKにしてもらいます。
.rubocop.yml に下記を追加。
Layout/IndentationConsistency:
  EnforcedStyle: rails
これで指摘されなくなりました。
追記
当初、上記で参考にしたGitHubからそのままコピペして Style/IndentationConsistency: としていたのですが、気付いたら下記のエラーが出ていました。
.rubocop.yml: Style/IndentationConsistency has the wrong namespace - should be Layout
RuboCop のバージョンアップで名前が Style から Layout に変わったそうです。
0 件のコメント:
コメントを投稿