rails helper递归阻塞奇怪的行为

时间:2012-12-03 13:20:29

标签: ruby-on-rails view-helpers

以下代码应接受嵌套代码并在'li'标记中生成

def sidebar_link(text,link, color = nil)
  recognized = Rails.application.routes.recognize_path(link)
  output = ""
  content_tag(:li, :class => ( "sticker sticker-color-#{color}" if color) ) do
  if recognized[:controller] == params[:controller] && recognized[:action] == params[:action]
    output << link_to( text, link, :class => 'lead')
  else
    output << link_to( text, link) 
  end
  output << yield if block_given?
  raw output
 end
end
在HAML视图中

      %ul
        = sidebar_link 'Tickets', tickets_path, :orange do
          %ul.sub-menu
            = sidebar_link "Service Requests #{ServiceRequest.all.count}", service_requests_path
        = sidebar_link 'Problems', problems_path, :green
        %li.divider
        = sidebar_link 'Clients', clients_path, :blueDark
        = sidebar_link  'Services', services_path, :red do
          %ul.sub-menu
            = sidebar_link 'Categories', categories_path

除第一个链接外,这会产生正确的HTML。输出不包含“Tickets”字样,但其他一切似乎都没问题。

那么为什么会出现这种奇怪的行为呢?助手递归会混淆“输出”变量吗?

1 个答案:

答案 0 :(得分:1)

我找到了明确使用&amp; block的解决方案,如下所示

def sidebar_link(text,link, color = nil, &block)
 recognized = Rails.application.routes.recognize_path(link)
 output = ""
 content_tag(:li, :class => ( "sticker sticker-color-#{color}" if color) ) do
  output << link_to( text, link, :class => ( 'lead' if recognized[:controller] == params[:controller] && recognized[:action] == params[:action]) )
  output << capture(&block) if block_given?
  raw output
 end
end