¿Cómo capturar un bloque en la clase secundaria de un ayudante?

Estoy intentando hacer lo siguiente:

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

Either give a string (or symbol) to the method heading, or a block.

En vista:

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

(nota la getmh is just for this example, the PModuleHelper is returned by some other process in my application, so no need to comment on this or suggest to make heading a normal helper method, not a class-method)

Unfortunately I always get the following error:

wrong number of arguments (0 for 1)

with linenumber for the capture(&block) llamada.

¿Cómo se utiliza? capture inside own helper class?

preguntado el 27 de agosto de 11 a las 17:08

1 Respuestas

I'd do something like this :

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

I can't guarantee this will work, because I had this error : undefined method 'output_buffer=' instead of the one you're mentioning. I haven't been able to reproduce yours.

Respondido 28 ago 11, 22:08

that nearly does it! One error, though: content_tag must be delegated, too (in my original question I updated I included the helpers, now)! Then everything works. And seems to be very logical, why it does! - Markus

would look more the rails way with delegate :capture, :content_tag, :to => :parent ;-) - Markus

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.