LoginSignup
6
2

More than 3 years have passed since last update.

RuboCopのAbcSizeチェックの対応

Last updated at Posted at 2020-03-15

Rubyの静的コード解析をやってくれるRuboCopをRails開発に導入しました。そこで発生したAbcSizeチェックについての作業メモ。

AbcSizeとは

実装したメソッドに対してRuboCop君が計算してくれるスコア。
以下の3つのカウントが評価対象。

  • Assignment : 代入
  • Branch : メソッド呼び出し
  • Condition : 条件

デフォルトで15を超えると警告が出て、もっとスコア下げてねと言われる。

警告が出たメソッド

ユーザーのサインイン機能を担う、こちらのSessionsController.create

sessions_controller.rb
def create
  @user = User.find_by(email: params[:session][:email].downcase)
  if @user&.authenticate(params[:session][:password])
    # ユーザーログイン後にユーザ情報のページにリダイレクトする
    log_in @user
    params[:session][:remember_me] == '1' ? remember(@user) : forget(@user)
    recdirect_back_or @user
  else
    # エラーメッセージを作成する
    flash.now[:danger] = 'Invalid email/password combination'
    render 'new'
  end
end

出た警告はこちら。

Assignment Branch Condition size for create is too high. <2, 19, 4> 19.52/15",

どうやらスコアは19.52らしく、評価項目毎だとこうなってる。

  • Assignment => 2
  • Branch => 19
  • Condition => 4

対策

...とはいえ現状可読性は問題ない(主観)し、メソッド抽出が必要なほどロジックは複雑ではないので、AbcSizeチェックの基準値を調整しておく。

.rubocop.yml

Metrics/AbcSize:
  Max: 20

おわりに

デフォルトの15を下回れるような解決方法があれば後ほど更新したい。

ちなみにRuboCop自体の.rubocop_todo.ymlでは基準値が18になっているという...

6
2
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
6
2