Tom Clowers
Tom Clowers

Reputation: 141

DRY Rails array displayed as 2 Bootstrap rows

Here I have a pretty basic Rails array and I'm displaying it as a 2x2 grid of butons. I'm using Bootstrap 3 and I have two different row divs with two different col-md-6 divs on each. I'm writing more or less the exact same line of code 4 times and iIf it weren't for the two 'row' divs, I could just DRY this up. How do I handle this?

<div id="answers">
    <div class="row">
        <div class="col-md-6"><%= button_to @choices[0].answer, "#", class: "btn btn-default btn-answer", method: :post %></div>
        <div class="col-md-6"><%= button_to @choices[1].answer, "#", class: "btn btn-default btn-answer", method: :post %></div>
    </div>
    <div class="row">
        <div class="col-md-6"><%= button_to @choices[2].answer, "#", class: "btn btn-default btn-answer", method: :post %></div>
        <div class="col-md-6"><%= button_to @choices[3].answer, "#", class: "btn btn-default btn-answer", method: :post %></div>
    </div>
</div>

Upvotes: 0

Views: 458

Answers (1)

Beartech
Beartech

Reputation: 6421

      <% choices.each_slice(2) do |first_two| %>
          <div class="row">
             <div class="col-md-6"><%= button_to first_two[0].answer , "#", class: "btn btn-default btn-answer", method: :post %></div>
             <div class="col-md-6"><%= button_to first_two[1].answer, "#", class: "btn btn-default btn-answer", method: :post %></div>
          </div>
      <% end %>

DRYs it up some. You could even make each half of the code around <%= first_two[1] %> a variable and do each line like <%= puts variable_1 + first_two[0] + variable_2 %>

or even more DRY:

<% choices.each_slice(2) do |first_two| %>
          <div class="row">
             <% first_two.each do |choice| %>
               <div class="col-md-6"><%= button_to choice.answer, "#", class: "btn btn-default btn-answer", method: :post %></div>
             <% end %>
          </div>
<% end %>

If you are going to do this over and over on a page I would define a helper method that does all of this, that way you just call the helper method with the array and it spits them all out.

Upvotes: 2

Related Questions