【发布时间】:2020-08-01 22:07:06
【问题描述】:
我最近开始使用 Rubocop 来“标准化”我的代码,它帮助我优化了很多代码,并帮助我学习了很多 Ruby“技巧”。我知道我应该使用自己的判断并在必要时禁用警察,但我发现自己非常坚持以下代码:
def index
if params[:filters].present?
if params[:filters][:deleted].blank? || params[:filters][:deleted] == "false"
# if owned is true, then we don't need to filter by admin
params[:filters][:admin] = nil if params[:filters][:admin].present? && params[:filters][:owned] == "true"
# if admin is true, then must not filter by owned if false
params[:filters][:owned] = nil if params[:filters][:owned].present? && params[:filters][:admin] == "false"
companies_list =
case params[:filters][:admin]&.to_b
when true
current_user.admin_companies
when false
current_user.non_admin_companies
end
if params[:filters][:owned].present?
companies_list ||= current_user.companies
if params[:filters][:owned].to_b
companies_list = companies_list.where(owner: current_user)
else
companies_list = companies_list.where.not(owner: current_user)
end
end
else
# Filters for deleted companies
companies_list = {}
end
end
companies_list ||= current_user.companies
response = { data: companies_list.alphabetical.as_json(current_user: current_user) }
json_response(response)
end
除其他外,我得到的错误如下:
C: Metrics/AbcSize: Assignment Branch Condition size for index is too high. [<13, 57, 16> 60.61/15]
我了解它背后的数学原理,但我不知道如何简化此代码以达到相同的结果。
有人可以给我一些指导吗?
提前致谢。
【问题讨论】:
-
与其对这段特定的代码进行评论,我建议您阅读 Martin Fowler 的 Refactoring 或 Sandi Metz 的 99 Bottles of OOP 的副本。您将学到很多关于减少复杂代码和改进设计的方法。
-
@AndyWaite 谢谢你的建议。我查阅了您推荐的 Martin Fowler 的书,并已开始阅读。
标签: ruby ruby-on-rails-5 rubocop