Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to capture a block in a helper's child class?

I'm trying to do the following:

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.

In View:

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

(note the 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) call.

How to use capture inside own helper class?

like image 752
Markus Avatar asked Aug 27 '11 17:08

Markus


1 Answers

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.

like image 62
Benoit Garret Avatar answered Sep 19 '22 15:09

Benoit Garret