【发布时间】:2012-12-19 22:07:21
【问题描述】:
我正在使用 Ruby on Rails 3.2.9 和 Ruby 1.9.3。我有以下case 声明:
case
when private?
case
when not_active? then [:a, :b, :c, :d]
when active? then raise "private cannot be active"
else raise "not recognized"
end
when shared?
case
when not_active? then [:a, :b, :c]
when active? then raise "shared cannot be active"
else raise "not recognized"
end
when public?
case
when not_active? then [:a, :b]
when active? then [:a]
else raise "not recognized"
end
else raise "not recognized"
end
如何重构上述代码?
【问题讨论】:
-
@Andrew Marshall - 我不明白您为什么(至少)删除了
ruby-on-rails标记,因为可能有一些 RoR 方法可以帮助重构问题中发布的代码. -
您能详细解释一下
active?和not_active?方法吗?它们是互补的吗,我的意思是not_active? == !active?是这样吗? -
你的代码怎么能转到
raise "not recognized"? -
@Khaled - 是的,它们是互补的(not_active? == !active?# => true)。
-
@oldergod - 你可能是对的,因为方法是互补的。
标签: ruby-on-rails ruby refactoring switch-statement