【问题标题】:How to make this ruby method less ugly (nesting)如何让这个 ruby​​ 方法不那么难看(嵌套)
【发布时间】:2009-10-17 14:44:27
【问题描述】:

我有一个辅助方法可以为一些控制器创建导航链接。

  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

我不喜欢这种深度嵌套的结构,以及多余的&lt;&lt; 和其中一行的结尾。

我怎样才能重写它,使它不会像那样嵌套(在更少的行中)并且没有长行(

【问题讨论】:

    标签: ruby-on-rails ruby coding-style nested


    【解决方案1】:

    使用部分 - 将所有内容都放在返回关闭中,然后使用render :partial =&gt; ...

    【讨论】:

      【解决方案2】:

      考虑使用 markaby 之类的东西来代替 content_tag;它使您的助手更具可读性。另见railscast

      【讨论】:

        【解决方案3】:

        从内到外构建它:

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

        【讨论】:

          猜你喜欢
          • 2011-02-22
          • 2011-03-12
          • 2017-01-11
          • 1970-01-01
          • 1970-01-01
          • 2022-10-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多