2009-10-17 25 views
1

我有一個幫助器的方法,爲一些控制器創建導航鏈接。如何使這個紅寶石方法不那麼醜(嵌套)

def gen_associations(controllers) 
    content_for :leftnav do 
     sorted_controllers = controllers.sort 
     returning String.new do |content| 
     content << content_tag(:h3, "Associations") << 
     content_tag(:ul, :class => "nav") do 
      sorted_controllers.collect do |c| 
      content_tag("li", :class => ("last" if c == sorted_controllers.last)) do 
       link_to(c.humanize, eval("admin_#{c}_url")) 
      end 
      end 
     end 
     end 
    end 
    end 

我不喜歡這樣的深度嵌套的結構,而額外<<和線之一的結束。

我怎樣才能重寫它,所以它沒有像這樣嵌套(更少的行)和沒有長行(< 80個字符)?

回答

2

從內到外的構建:

def gen_associations(controllers) 
    sorted_controllers = controllers.sort 

    list_items = 
     sorted_controllers.collect do |c| 
     content_tag("li", :class => ("last" if c == sorted_controllers.last)) do 
      link_to(c.humanize, eval("admin_#{c}_url")) 
     end 
     end 

    list = content_tag(:ul, list_items.join, :class => "nav") 

    content_for :leftnav do 
     content_tag(:h3, "Associations") << list 
    end 
    end 

我可能會移動content_for到視圖或部分,只是有gen_associations()返回list

... 
<% content_for :leftnav do %> 
    <h3>Associations</h3> 
    <%= gen_associations(@controllers) %> 
<% end %> 
... 
7

使用部分 - 把一切都放在那裏返回封閉,然後用render :partial => ...