如何在Helper的子类中捕获一个块?

16

我想做以下操作:

module ApplicationHelper

   class PModuleHelper
     include ActionView::Helpers::TagHelper
     def heading(head = "", &block)
       content = block_given? ? capture(&block) : head.to_s
       content_tag :h3, content, :class => :module_header
     end
   end

    def getmh
        PModuleHelper.new
    end

end
heading 方法要么接受一个字符串(或符号),要么接受一个代码块作为参数。

在视图中:

<% mh = getmh %>
<%= mh.heading :bla %> // WORKS
<%= mh.heading do %>   // FAILS
    test 123
<% end %>

(请注意,getmh 只是为了举例说明,PModuleHelper 是由应用程序中的其他进程返回的,因此不需要评论或建议将 heading 设为普通帮助方法而不是类方法)

不幸的是,我总是得到以下错误:

wrong number of arguments (0 for 1)

在自己的帮助器类中如何使用capture并获取其行号?

1个回答

13

我会这样做:

module Applicationhelper
  class PModuleHelper

    attr_accessor :parent

    def initialize(parent)
      self.parent = parent
    end

    delegate :capture, :content_tag, :to => :parent

    def heading(head = "", &block)
      content = block_given? ? capture(&block) : head.to_s
      content_tag :h3, content, :class => :module_header
    end
  end

  def getmh
    PModuleHelper.new(self)
  end
end

我不能保证以下方法一定有效,因为我曾经遇到过这个错误:undefined method 'output_buffer=',而不是你提到的那种错误。我无法重现你遇到的错误。

我不能百分之百确定这个方法能够解决你的问题,因为我曾经遇到过一个错误:undefined method 'output_buffer=',而不是你提到的那个错误。我没有办法重现你的错误。


几乎完成了!不过还有一个错误:content_tag 也必须被委托(在我更新的原始问题中,我包括了帮助程序)!然后一切都可以正常工作。而且似乎非常合乎逻辑,这就是为什么它能够正常工作! - Markus
使用 delegate :capture, :content_tag, :to => :parent 更符合 Rails 的风格 ;-) - Markus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接