【问题标题】:How do I refactor my Rails partial?如何重构我的 Rails 部分?
【发布时间】:2014-04-25 03:17:29
【问题描述】:

我有一个相对较深的条件句的部分,我很好奇这是否适用于部分?

我正在循环浏览一系列游戏并根据游戏日期是否与今天的日期匹配打印“是”或“否”。

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

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    我会将所有内容都投入到某种辅助方法中:

    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
    

    我不确定您的 todaynext_game 变量/方法具体做什么,或者您是否真的想出于任何原因保留这些 i/x 局部变量,但如果您这样做或他们有一些其他的额外含义,请扩展您的问题。

    顺便说一句,我推荐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 %>
    

    【讨论】:

    • 谢谢保罗。很有帮助。
    【解决方案2】:

    看起来这对你来说很好,但我不确定你为什么有两个变量或者为什么你有next_game

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

    【讨论】:

      猜你喜欢
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多