1
1

More than 1 year has passed since last update.

Ruby rubocop 「Metrics/CyclomaticComplexity: Cyclomatic complexity for index is too high.」エラーへの対処

Last updated at Posted at 2021-12-07

1.状況

ruby 2.6.3p62
rails 5.2.6

Gemfile にコーディングを精査するrubocopをインストールして実行したところ
以下のような警告が発生した

app/controllers/public/posts_controller.rb:3:3: C: Metrics/CyclomaticComplexity: Cyclomatic complexity for index is too high. [11/7]
  def index ...

該当箇所のコントローラーファイルは以下のようになっていた。

app/controllers/public/posts_controller.rb
class Public::PostsController < ApplicationController

def index
    # デフォルトは更新日時の降順に並べる
    @posts = Post.all.order(updated_at: 'DESC').page(params[:page]).per(10)
    @range = params[:range] # 並べ替え選択時のページネーションを場合分け
    case @range
    when "投稿Noが新しい順に"
      @posts = Post.all.order(id: 'DESC').page(params[:page]).per(10)
    when "投稿Noが古い順に"
      @posts = Post.all.order(id: 'ASC').page(params[:page]).per(10)
    when "更新日時が新しい順に"
      @posts = Post.all.order(updated_at: 'DESC').page(params[:page]).per(10)
    when "更新日時が古い順に"
      @posts = Post.all.order(updated_at: 'ASC').page(params[:page]).per(10)
    when "ジャンルidが大きい順に"
      @posts = Post.all.order(genre_id: 'DESC').page(params[:page]).per(10)
    when "ジャンルidが小さい順に"
      @posts = Post.all.order(genre_id: 'ASC').page(params[:page]).per(10)
    when "質問者idが大きい順に"
      @posts = Post.all.order(member_id: 'DESC').page(params[:page]).per(10)
    when "質問者idが小さい順に"
      @posts = Post.all.order(member_id: 'ASC').page(params[:page]).per(10)
    when "PV数の多い順に"
      @posts = Post.all.order(impressions_count: 'DESC').page(params[:page]).per(10)
    when "PV数の少ない順に"
      @posts = Post.all.order(impressions_count: 'ASC').page(params[:page]).per(10)
    end
  end
.....

Rubyの循環的複雑度をチェックした際にデフォルト値(7)をオーバーしてたために
発生している警告である。

2.対処法

Rubyの循環的複雑度を変えるために「.rubocop.yml」の記述を更新する。
具体的に以下とする

rubocop.yml
# Rubyの循環的複雑度をデフォルト7から変更
CyclomaticComplexity:
  Max: 13

自分の場合「CyclomaticComplexity:」の記述は元々記載されていなかったが
「Max: 7」として処理されていた。

.rubocop.ymlの記述を更新後は該当警告文が発生しなくなった。

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