2014-03-19 45 views
0

我有一個部分的條件相對較深,我很好奇這是否適合部分?如何重構我的Rails部分?

根據遊戲日期是否與今天的日期相匹配,我騎自行車遊戲並打印YES或NO。

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

謝謝!

回答

1

我會拋出一大堆變成某種輔助方法:

應用/視圖/ your_controller/your_view/_your_partial.html.erb

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

應用程序/傭工/ 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 

我不知道你的todaynext_game變量/方法做具體,或者如果你真的想保持出於某種原因這些i/x局部變量,但如果你這樣做或者他們有其他一些額外的含義,請擴展你的問題。

順便說一句,我建議keeping instance variables out of your partials

應用程序/視圖/ your_controller/your_view.html.erb

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

應用程序/視圖/ your_controller/_your_partial.html.erb

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

謝謝保羅。很有幫助。 – reknirt

1

看起來這會工作得很好了你,但我不知道爲什麼你有兩個變量,或者你爲什麼next_game

<% @games.each do |game| %> 
    <% if game.date == Date.today %> 
    YES 
    <% else %> 
    NO! 
    <% end %> 
<% end %>