Rails 查看助手显示徽章和文本

Rails view helper display badge and text

我有一个正在使用 Rails 的应用程序 3.2.x 和 Bootstrap 2. 我有一个视图助手,returns 不同的文本基于呼叫的状态和属性。

def status(call)
   if call.call_status == "open" && call.transfer_date > Time.zone.now + 15.minutes
     "Scheduled"
   elsif call.wait_return == "yes" && call.call_status == "open"
     "Active/Wait and Return"
   elsif call.call_status == "close"
     "Closed Call"
   elsif call.call_status == "cancel"
     "Cancelled Call"
   else
     "Active"
   end
 end

我想将其重构为每个条件的文本 returns 一个 bootstrap 徽章,其中包含文本。我查看了 content_tag 的 API 文档,我认为这就是我所需要的,但我不是 100% 确定如何完成这项工作。

任何帮助或重构建议将不胜感激。

我会先把那个大方法分成小方法,像这样:

class Call
  def scheduled?
    call_status == "open" && call.transfer_date > Time.zone.now + 15.minutes
  end

  def closed?
    call_status == "close"
  end

  ...
end

那么您的 status 方法将如下所示:

def status(call)
  text = case
    when call.scheduled?
      "Scheduled"
    when call.cancelled?
      "Active/Wait and Return"
    when call.closed?
      "Closed Call"
  end
  content_tag(:span, text, class: "badge")
end 

希望对您重构代码有所帮助。