代码之家  ›  专栏  ›  技术社区  ›  Shpigford

我如何重构这些除非语句以提高块的效率?

  •  1
  • Shpigford  · 技术社区  · 16 年前

    我正试图根据URL中是否有“订单”参数(即example.com/photos?order=views)向以下链接集添加一个“当前”类。我需要一些帮助来重构它,这样它就不会那么笨重了。

    <% unless params[:order] != 'created_at' %>
        <%= link_to "Recently Posted", photos_path, :class => 'current' %> 
    <% else %>
        <%= link_to "Recently Posted", photos_path %> 
    <% end %>
    <span class="pipe">|</span> 
    <% unless params[:order] != 'comments' %>
        <%= link_to "Most Commented", photos_path + "?order=comments", :class => 'current' %> 
    <% else %>
        <%= link_to "Most Commented", photos_path + "?order=comments" %> 
    <% end %>
    <span class="pipe">|</span> 
    <% unless params[:order] != 'views' %>
        <%= link_to "Most Viewed", photos_path + "?order=views", :class => 'current' %>
    <% else %>
        <%= link_to "Most Viewed", photos_path + "?order=views" %>
    <% end %>
    
    2 回复  |  直到 16 年前
        1
  •  4
  •   tig Charlie Martin    16 年前

    例如,您可以使用助手:

    <%= link_to_photos_with_order 'created_at', "Recently Posted" %>
    <span class="pipe">|</span>
    <%= link_to_photos_with_order 'comments', "Most Commented" %>
    <span class="pipe">|</span>
    <%= link_to_photos_with_order 'views', "Most Viewed" %>
    

    def link_to_photos_with_order order_by, title
      url = photos_path(:order => (order_by != 'created_at' ? order_by : nil))
      unless params[:order] != order_by
        link_to title, url, :class => 'current'
      else
        link_to title, url
      end
    end
    

    另一种方法是使用order_by=>标题,但更丑

        2
  •  1
  •   Avdi    16 年前

    def link_to_ordering(params, ordering, title)
      css_class = params[:order] == ordering ? 'current' : ''
      link_to(title, photos_path(:order => ordering), :class => css_class)
    end
    

    然后只需调用例如:

    <%= link_to_ordering(params, "Most Commented", "comments") %>
    

    在你看来。