减少代码冗余

时间:2017-05-30 08:55:21

标签: html ruby-on-rails performance ruby-on-rails-4 optimization

我有一个rails应用程序,其中包含以下代码

            <ul class="sortable grid row">
            <% @videouploads.each do |video_upload| %>
                <% if video_upload.category == 'モノナビ' && video_upload.priority == 1 %>
                    <%= render partial: 'adminrow', :locals => {:video_upload => video_upload } %>
                <% end %>
            <% end %>
            </ul>

我必须为video_upload.priority == 1编写此代码10次,其中优先级从1更改为10.如何避免代码重复或者我有什么是最佳解决方案?

2 个答案:

答案 0 :(得分:0)

循环优先级

<% priorities = (1..10).to_a %>
<% priorities.each do |priority| %>
  <ul class="sortable grid row">
    <% @videouploads.each do |video_upload| %>
      <% if video_upload.category == 'モノナビ' && video_upload.priority == priority %>
        <%= render partial: 'adminrow', :locals => {:video_upload => video_upload } %>
      <% end %>
    <% end %>
  </ul>
<% end %>

答案 1 :(得分:0)

<% (1..10).each do |inc| %>    
  <ul class="sortable grid row">
    <% @videouploads.each do |video_upload| %>
      <% if video_upload.category == 'モノナビ' && video_upload.priority == inc %>
      <%= render partial: 'adminrow', :locals => {:video_upload => video_upload } %>
      <% end %>
    <% end %>
  </ul>
<% end %>

这个怎么样?