0

I have a partial with relatively deep conditionals and I was curious if this is appropriate for a partial?

I'm cycling through an array of Games and printing YES or NO based on whether or not the date of the game matches today's date.

<% i = 0 %>
<% x = 0 %>
<% @games.each do |game| %>
  <% if game.date.strftime("%_m/%d")[1..-1] == today %>
     YES!
     <% i = 1 %>
  <% else %>
     <% unless i == 1 %>
     NO!
     <% i = 1 %>
     <% x = 1 %>
     <%= next_game %>
     <% end %>
  <% end %>
<% end %>

Thanks!

reknirt
  • 2,237
  • 5
  • 29
  • 48

2 Answers2

1

It seems like this would work just fine for you, but I'm not sure why you have two variables or why you have next_game

<% @games.each do |game| %>
  <% if game.date  == Date.today %>
    YES
  <% else %>
    NO!
  <% end %>
<% end %>
toolz
  • 871
  • 6
  • 12
1

I would throw the whole lot into some kind of helper method:

app/views/your_controller/your_view/_your_partial.html.erb

<% @games.each do |game| %>
  <%= played_today(game) %>
<% end %>

app/helpers/your_helper.rb

def played_today(game) # or whatever you want to call it
  # Use Date.current to be timezone aware, otherwise just Date.today
  game.date == Date.current ? 'YES' : 'NO'
end

I'm not sure what your today and next_game variables/methods do specifically, or if you really want to keep those i/x local variables for whatever reason, but if you do or they have some other extra meaning, please expand on your question.

As an aside, I'd recommend keeping instance variables out of your partials:

app/views/your_controller/your_view.html.erb

<% = render 'your_partial', games: @games %>

app/views/your_controller/_your_partial.html.erb

<% games.each do |game| %>
  <%= played_today(game) %>
<% end %>
Community
  • 1
  • 1
Paul Fioravanti
  • 16,423
  • 7
  • 71
  • 122