开发者

undefined method `output_buffer=' for content_tag with block

开发者 https://www.devze.com 2023-02-20 08:19 出处:网络
in lib/my_lib.rb class MyLib include ActionView::Helpers::TagHelper def foo content_tag :di开发者_运维知识库v do

in lib/my_lib.rb

class MyLib
    include ActionView::Helpers::TagHelper

    def foo
      content_tag :di开发者_运维知识库v do
         "hello"
       end
    end
end

gives a

require 'lib/my_lib' ;MyLib.new.foo
NoMethodError: undefined method `output_buffer=' for #<MyLib:0x7f3209aaa450>
    from /var/lib/gems/1.8/gems/actionpack-3.0.5/lib/action_view/helpers/capture_helper.rb:175:in `with_output_buffer'
    from /var/lib/gems/1.8/gems/actionpack-3.0.5/lib/action_view/helpers/capture_helper.rb:40:in `capture'
    from /var/lib/gems/1.8/gems/actionpack-3.0.5/lib/action_view/helpers/tag_helper.rb:77:in `content_tag'
    from ./lib/my_lib.rb:6:in `foo'
    from (irb):1


Is there a particular reason you can't put this logic inside a view?

content_tag was made for the View environment, and was not intended to be called from within a controller or other library. You will need to set up your MyLib class as a view.

While I recommend that you re-think, and re-smell your code and design that has brought you to the point of needing this, you can accomplish what you want by subclassing from ActionView::Base.

class MyLib < ActionView::Base
  include ActionView::Helpers::TagHelper

  def foo
    content_tag :div do
      "hello"
    end
  end
end


If you can't subclass ActionView::Base because you already need to subclass something else, you can also include ActionView::Context:

class MyLib
  include ActionView::Helpers::TagHelper
  include ActionView::Context

  def foo
    content_tag :div do
      "hello"
    end
  end
end

This helped me when subclassing WillPaginate::ActionView::LinkRenderer to make its output Bootstrap-compatible.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号