Rails:干掉相似但不同的观点

时间:2013-01-11 13:32:14

标签: ruby-on-rails view

我有一对非常相似的视图,它们呈现几乎相同的信息,只在一个视图中有几个额外的列,而在另一个视图中,行链接略有不同的嵌套资源。我最初的方法是通过使用部分然后在整个视图中放置条件来保持DRY。结果部分看起来像这样:

<div id='overview_table'>
  <div id="overview_header">
    <span id="sort_title" class="title cell">Title<span id="publication_sort_arrow"> &darr;</span></span>
    <span id="sort_author" class="author cell">Author</span>
    <span id="sort_status" class="status cell">Status</span>
    <% if @user.present? %>
        <span id="sort_impression_date" class="date cell">Date</span>
        <span id="sort_impression_vote" class="votes cell">Votes</span>
        <span id="sort_children_total" class="children_total cell">Replies</span>
    <% end %>
  </div>
  <span id="sort_method">title ASC</span>
  <% @publications.each do |publication| %>
    <div class='<%= cycle("odd", "even") %>'>
        <% if @user.present? %>
            <% link = [@user, publication] %>
        <% else %>
          <% link = [@group, publication] %>
        <% end %>
        <%= link_to(link, :remote => true) do %>
            <span class="title cell"><%= publication.full_title %></span>
            <span class="author cell"><%= publication.authors %></span>
            <span class="status cell"><%= publication_status(publication.status) %></span>
            <% if @user.present? %>
                <span class="date cell"><% if publication.impression_date %><%= publication.impression_date.strftime("%B %d, %Y") %><% end %></span>
                <span class="votes cell"><% if publication.impression_vote %><%= publication.impression_vote.to_i %><% end %></span>
                <span class="children_total cell"><% if publication.impression_vote %><%= publication.children_total %><% end %></span>
            <% end %>
        <% end %>
    </div>
<% end %>

它运行良好,但代码感觉很乱。我最终把它们分成了两个不同的视图,尽管现在有很多重复的代码。两种方法都不合适。还有其他方法我不考虑吗?

1 个答案:

答案 0 :(得分:0)

这里有不同的策略,但在这种情况下,如果你只是添加一些字段,我会做这样的事情(这与你正在做的类似)。

在我的控制器中,我将一些标记值设置为true:

@show_val_extra=true 

并且在我看来(可能是部分代码而不是示例中的内联代码):

  <%="something here" unless @show_val_extra.nil? %>

无论你要检查什么,控制器中管理视图的其他问题对我来说都很难看。 YMMV,但这是我要做的,因为它基本上使它成为单个值,并在您需要不同信息时进行单一检查。通常情况下,它位于多个地方,但你有多个地方的内容,如果情况出现,进一步的重构很容易。