我怎么能重构这个方法?

时间:2014-11-07 11:41:11

标签: ruby-on-rails ruby ruby-on-rails-3 refactoring

我有这个方法,我在控制器中的if条件下继续执行。

def continue_bulk_action
 (@non_deleteable_invoices < 1 && params[:destroy] == "Delete") || (@unsendable_invoices == 0 && params[:send] == "Send") ||(params[:destroy] != "Delete" && params[:send] != "Send")
end

我如何重构这种方法?

3 个答案:

答案 0 :(得分:3)

IMO这个更容易阅读,它也更有效:

def continue_bulk_action
  if params[:destroy] == "Delete"
    @non_deleteable_invoices < 1
  elsif params[:send] == "Send"
    @unsendable_invoices == 0
  else
    true
  end
end

答案 1 :(得分:1)

我会从每个测试中提取 含义 。这使得代码更具表现力。

def continue_bulk_action
  delete_with_no_deletable_invoices ||
  send_with_no_unsendable_invoices ||
  not_delete_or_send
end

def delete_with_no_deletable_invoices
  @non_deleteable_invoices < 1 && params[:destroy] == "Delete"
end

def send_with_no_unsendable_invoices
  @unsendable_invoices == 0 && params[:send] == "Send"
end

def not_delete_or_send
  params[:destroy] != "Delete" && params[:send] != "Send"
end

答案 2 :(得分:0)

我想您正在尝试在其他3种方法中重用continue_bulk_action方法。为什么不将Destroy / Send条件移动到将要使用它们的方法中,而不是将它们保存在一个方法中?