什么是'分配分支条件大小太高'以及如何解决它?

THp*_*ubs 94 ruby ruby-on-rails code-metrics rubocop

在我的Rails应用程序中,我Rubocop用来检查问题.今天它给了我一个这样的错误:Assignment Branch Condition size for show is too high.这是我的代码:

def show
  @category = Category.friendly.find(params[:id])
  @categories = Category.all
  @search = @category.products.approved.order(updated_at: :desc).ransack(params[:q])
  @products = @search.result.page(params[:page]).per(50)
  rate
end
Run Code Online (Sandbox Code Playgroud)

这是什么意思,我该如何解决?

cha*_*ad_ 96

分配分支条件(ABC)大小是方法大小的度量.它主要通过计算A ssignments,B ranches 和C onditional语句的数量来确定. (更多详情..)

要减少ABC大小,您可以将其中一些分配移动到before_action调用中:

before_action :fetch_current_category, only: [:show,:edit,:update] 
before_action :fetch_categories, only: [:show,:edit,:update] 
before_action :fetch_search_results, only: [:show,:edit,:update] #or whatever

def show
  rate
end

private

def fetch_current_category
  @category = Category.friendly.find(params[:id])
end

def fetch_categories
  @categories = Category.all
end

def fetch_search_results
  @search = category.products.approved.order(updated_at: :desc).ransack(params[:q])
  @products = @search.result.page(params[:page]).per(50)
end
Run Code Online (Sandbox Code Playgroud)

  • 万分感谢。现在代码看起来可读性很好,但是这不是使文件变大了吗?更多代码?好吗? (2认同)
  • 如果您在其他操作中需要这些变量,则代码更少。 (2认同)
  • 谢谢.我把它指向维基百科.我希望这应该更可靠一点. (2认同)