我想将某种逻辑抽象到一个观察助手身上。 在我看来,这个想法是能够做这样的事情:
<ul class="nav">
<% pages_for_section( over ) do |page| %>
<li><%= page.menu_text %></li>
<% end %>
</ul>
我目前的做法就是让这个帮手变成这样:
def pages_for_section(section_slug, &block)
out = []
pages_in_section = @pages.select { |p| p.section.slug == section_slug }
pages_in_section.each do |page|
out << yield(page)
end
return out
end
具体来说, out<<< page( page)
部分正在困扰我。 它有效, 但似乎不是正确的 DRY 方式。 因此, 如果我想在视图中添加一个变量, 我将需要将它添加到块辅助器中, 并生成调用 。
底线 : 我想将一个从滚动页面到滚动的变量输入到被选中的区块。 这是最佳做法吗? 还是有更好、更可读的替代品?
理想的情况是,我想做一些事情,比如:
<ul class="nav">
<% each_page_in_section( over ) do %>
<li><%= page.menu_text %> <%= another_variable %></li>
<% end %>
</ul>
和帮手 看着类似的东西 概念上是这样的:
def pages_for_section(section_slug, &block)
pages_in_section = @pages.select { |p| p.section.slug == section_slug }
pages_in_section.each do |page|
another_variable = "I m cool"
# the `page` and the `another_variable` variable will automatically
# be available/copied to the block
yield
end
end
谢谢