gem_finder_1991
gem_finder_1991

Reputation: 27

Reduce code redundancy

I have a rails application which has some following code

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

I have to write this code 10 times for video_upload.priority == 1 where priority changes from 1 to 10. How do I avoid code duplication or do I have what is the best solution ?

Upvotes: 0

Views: 295

Answers (2)

mehtasuraj09
mehtasuraj09

Reputation: 139

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

How about this ?

Upvotes: 0

Deepak Mahakale
Deepak Mahakale

Reputation: 23661

loop over the priorities

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

Upvotes: 1

Related Questions