Can't suppress output in nested block helper in rails 3

梦想与她 提交于 2020-01-14 03:07:11

问题


This one is sort of twisting my noodle.

I have something resembling this (in a rails 3 engine if that matters)

class Builder
  def initialize
    @foos = []
  end

  def foo(&block)
    @foos << helper.capture(&block) #helper being a class that is including ActionView::Helpers
  end

  def to_html
    @foos.join "\n"
  end
end

module ApplicationHelper
  def widget
    b = Builder.new
    yield b

    b.to_html
  end
end

#in a view somewhere
<%= widget do |b| %>
  <% b.foo do %>
    static content
  <% end %>
<% end %>

Everything is working out great, but that nested static content is getting output twice -- once where I want it, and once where widget was called.

From what I have read, capture is supposed to deal with this exact problem. I am pretty sure the problem stems from how I am calling capture (from a dummy proxy class that includes ActionView::Helpers), but the problem is that b.foo call is calling a method on a class instance, not from the context of something that will be mixed into the template.

Is there any way to get around this problem? Or am I approaching this from the wrong direction. I am trying to model something fairly involved and am really happy with the api, just can't seem to get passed this problem.


回答1:


If you modify the helper method to pass in self, which would be the current view instance, and then use this to capture, you might not have this issue. Substitute your use of helper for the provided view instance.



来源:https://stackoverflow.com/questions/4352167/cant-suppress-output-in-nested-block-helper-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!