我在控制器中有以下方法。当我运行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
最佳答案
哎呀!太高了!
这条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
关于ruby - some_method的循环复杂度太高,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47336195/