在视图中重构逻辑

时间:2015-02-17 15:23:59

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

目前,我在广告系列/ 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非常陌生,并不太确定我会怎么做。

非常感谢!

1 个答案:

答案 0 :(得分:4)

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

我无法弄清楚你的目的是什么,但是说你想根据不同的输入呈现不同的仪表板:

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 %>