我在控制器中有以下方法。当我运行lint
时,我收到错误
Cyclomatic complexity for some_method is too high
我在网上查了一下,看起来就像我写这个方法一样。我怎么能重写这个方法所以我没有得到lint错误?
def customer_order
if params[:customer_id].present? && !params[:order_id].present?
render_error :not_found, 'No info found for given customer id' \
unless @info.customer_id == params[:customer_id]
elsif params[:order_id].present? && !params[:customer_id].present?
render_error :not_found, 'No info found for given order id' \
unless @info.order_id == params[:order_id]
elsif params[:customer_id].present? && params[:order_id].present?
render_error :not_found, 'No info found for given customer id and order id’ \
unless @info.customer_id == params[:customer_id] &&
@info.order_id == params[:order_id]
end
end
答案 0 :(得分:1)
糟糕!太高了!
这个linting消息本质上意味着你有很多if
语句,开发人员很难保持直接。
我建议将每个if
语句的内容重构为它自己的方法。
def customer_order
if params[:customer_id].present? && !params[:order_id].present?
no_order_error
elsif params[:order_id].present? && !params[:customer_id].present?
no_info_error
...
end
def no_order_error
return if @info.customer_id == params[:customer_id]
render_error :not_found, 'No info found for given customer id'
end
def no_info_error
...
end
答案 1 :(得分:0)
一种方法是使每个条件都成为他们自己的方法。举个例子:
def customer_without_order(params)
params[:customer_id].present? && !params[:order_id].present?
end
您可能会发现确定何时出现错误的条件也可以保证这种处理。
答案 2 :(得分:0)
你可以减少一些冗余。
def customer_order
msg = case [params[:customer_id].present?, params[:order_id].present?]
when [true, false]
@info.customer_id == params[:customer_id] ?
nil : 'No info found for given customer id'
when [false, true]
@info.order_id == params[:order_id] ?
nil : 'No info found for given order id'
when [true, true]
@info.customer_id == params[:customer_id] && @info.order_id == params[:order_id] ?
nil : 'No info found for given customer id and order id’
else
nil
end
render_error(:not_found, msg) if msg
end