“分配分支条件大小过高”是什么意思,如何解决? (说明:此处为提问标题,无需回答)

157
在我的Rails应用程序中,我使用Rubocop来检查问题。今天它给了我一个类似这样的错误:show的Assignment Branch Condition大小太大。这是我的代码:
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

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


15
简单搜索发现 这个链接。它是 rubocop 表达“你的方法做了太多事情”的正式方式。 - D-side
在渲染过程中,所有定义的变量都会被使用吗? - Antarr Byrd
1个回答

163

赋值分支条件(ABC)大小是衡量方法大小的一种度量标准。它通常是通过计算赋值语句、分支和条件语句的数量来确定的。(更多细节…)

要减少 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

2
非常感谢。现在代码看起来更加易读了,但是它会不会让文件变得更大?需要更多的代码吗?这样好吗? - THpubs
6
如果您需要在其他操作中使用这些变量,则代码可以更少。 - chad_
我在这个方法上得到了同样的结果: # 将球绘制到此设备上下文中 def draw(dc) dc.setForeground(color) dc.fillArc(x, y, w, h, 0, 64 * 90) dc.fillArc(x, y, w, h, 64 * 90, 64 * 180) dc.fillArc(x, y, w, h, 64 * 180, 64 * 270) dc.fillArc(x, y, w, h, 64 * 270, 64 * 360) end我似乎无法保留代码块的布局!!! 这里到底发生了什么?这里根本没有赋值、分支或条件语句!!! - Lord Alveric
你有一些隐式的任务,其中你正在乘以数字。我会将它们移到常量中,这样你就不会在这些调用中重新评估相同的算术运算了。我不确定这是否会修复你的语法检查器的反馈,但肯定会使代码更加简洁。 :) - chad_
你可以像这样在一行中分配它们:RQ,RH,RT,RW = [90,180,270,360] .map { | i | i * 64 } - chad_
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接