视图中的重构逻辑

Refactoring logic in view

目前我对 campaign/show.html.erb:

有很多逻辑
<% if current_account.active? %>
  <% if @campaign.pending? %>
    <%= render 'campaigns/dashboard/nulldashboard' %>
  <% elsif @campaign.disabled? %>   
    <%= render 'campaigns/dashboard/disableddashboard' %>
  <% elsif @campaign.stats? %>   
    <%= render 'campaigns/dashboard/livedashboard' %>
  <% else %>
    <%= render 'campaigns/dashboard/awaitingdatadashboard' %>
  <% end %>
<% elsif current_account.pending? %>
  <%= render 'campaigns/dashboard/awaitingactivation' %>
<% end %>

在我的模型中:

  def active?; status == :active; end
  def finished?; status == :finished; end
  def pending?; status == :pending; end

我的问题是,我该如何清理这段代码?我是 rails 的新手,不太确定我会怎么做。

非常感谢!

您可以创建视图模型 - 有些人将其称为页面对象。

我不太明白你的目的是什么,但是说你想根据一些不同的输入呈现不同的仪表板:

class DashboardPage
  attr_reader :account, :campaign

  def initialize(account, campaign)
    @account, @campaign = account, campaign
  end 

  def render_dashboard?
    account.active? || account.pending?
  end

  def dashboard_template
    if account.active?
      active_account_template
    else
      'campaigns/dashboard/awaitingactivation'
    end
  end

  private

  def active_account_template
    # the inner if goes here...
  end
end

# In your controller

@page_object = DashboardPage.new(current_account, @campaign)

# In your view

<% if @page_object.render_dashboard? %>
  <%= render @page_object.dashboard_template %>
<% end %>