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(&block)呼叫的线路号。

如何capture在自己的助手类中使用?

4

1 回答 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='而不是你提到的那个。我无法复制你的。

于 2011-08-28T17:29:34.353 回答