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

除非语句使块更高效,否则如何重构这些语句?

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

    我正在尝试根据URL中是否存在“order”参数向以下一组链接添加“current”类。(例如,example.com/photos?命令=视图。我需要一些帮助来重构这个,这样它就不会那么粗了。

    <% 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 回复  |  直到 15 年前
        1
  •  4
  •   tig Charlie Martin    15 年前

    例如,您可以使用助手:

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

    另一种方法是将hash与order_by=>title一起使用,但它更丑

        2
  •  1
  •   Avdi    15 年前

    将逻辑提取到助手中:

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

    在你看来。