2009-10-17 80 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 => ...