Ruby on rails 3 如何使用两个或多个嵌套子对象创建自己的块辅助对象?

Ruby on rails 3 如何使用两个或多个嵌套子对象创建自己的块辅助对象?,ruby-on-rails-3,ruby-on-rails-3.1,Ruby On Rails 3,Ruby On Rails 3.1,我希望在我的视图中嵌套这样的内容: <%= helper_a do |ha| %> Content for a <%= ha.helper_b do |hb| %> Content for b <%= hb.helper_c do |hc| %> Content for c ... and so on ... <% end %> <% end %> <% end %>

我希望在我的视图中嵌套这样的内容:

<%= helper_a do |ha| %>
  Content for a
  <%= ha.helper_b do |hb| %>
    Content for b
    <%= hb.helper_c do |hc| %>
      Content for c
      ... and so on ...
    <% end %>
  <% end %>
<% end %>
我知道我可以将我的参数传递给
capture
,以便在视图中使用它们,因此类似这样的操作可以实现我的示例中的
|ha |

def helper_a(&block)
  content = capture(OBJECT_HERE, &block)
  content_tag :tag_a, content
end

但是我应该在哪里定义这个
对象呢
,尤其是它的类,以及如何在多个级别嵌套的情况下捕获每个块呢?

我提出了一些解决方案,但我远不是Rails模板系统的专家

第一个是使用实例变量:

def helper_a(&block)
  with_context(:tag_a) do
    content = capture(&block)
    content_tag :tag_a, content
  end
end

def helper_b(&block)
  with_context(:tag_b) do
    content = capture(&block)
    content_tag :tag_b, content
  end
end

def helper_c(&block)
  with_context(:tag_c) do
    content = capture(&block)
    content_tag :tag_c, content
  end
end

def with_context(name)
  @context ||= []
  @context.push(name)
  content = yield
  @context.pop
  content
end
其使用方式如下:

<%= helper_a do %>
  Content for a
  <%= helper_b do %>
    Content for b
    <%= helper_c do %>
      Content for c
      ... and so on ...
    <% end %>
  <% end %>
<% end %>
<%= helper_a do |context| %>
  Content for a
  <%= helper_b(context) do |context| %>
    Content for b
    <%= helper_c(context) do |context| %>
      Content for c
      ... and so on ...
    <% end %>
  <% end %>
<% end %>
其使用方式如下:

<%= helper_a do %>
  Content for a
  <%= helper_b do %>
    Content for b
    <%= helper_c do %>
      Content for c
      ... and so on ...
    <% end %>
  <% end %>
<% end %>
<%= helper_a do |context| %>
  Content for a
  <%= helper_b(context) do |context| %>
    Content for b
    <%= helper_c(context) do |context| %>
      Content for c
      ... and so on ...
    <% end %>
  <% end %>
<% end %>

满足于
b的内容
c的内容
... 等等
但是如果你所做的只是CSS样式和/或Javascript操作,我真的建议不要使用这两种解决方案中的任何一种。这确实使助手们变得复杂,可能会引入bug等等


希望这有帮助。

您真的需要将嵌套信息放入html类中吗?从您的示例中,我不想麻烦它,而是在CSS中使用“tag_a tag_b{property:value}”,或者在jQuery中使用“$('tag_a tag_b')”。你能告诉我你是否需要做CSS样式和/或Javascript操作以外的事情吗?这里添加的额外类只是示例,你是对的。根据“嵌套信息”的不同,可能还有其他一些变化。但是如果我需要不止一个嵌套级别,那么看起来我想做的太复杂了,所以我应该考虑一下我的应用程序设计。谢谢,这看起来有两种方法。几个小时前,我刚刚想到了一个类似的实例变量解决方案。并得出结论,思考为什么我的应用程序设计需要这么多嵌套级别,并针对这些级别做一些事情,而不是像地狱一样尝试嵌套;-)但如果我还必须这样做的话,我会用其中的一个。我一直都在做同样的事情,因为我脑子里想的东西太多了,所以我的头撞到了一个过度设计的解决方案上,然后退一步告诉自己“啊,我不需要这些废话”——)
<%= helper_a do |context| %>
  Content for a
  <%= helper_b(context) do |context| %>
    Content for b
    <%= helper_c(context) do |context| %>
      Content for c
      ... and so on ...
    <% end %>
  <% end %>
<% end %>