特定のロジックをビュー ヘルパーに抽象化したい。私の見解では、次のようなことができるようになるという考えです。
<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 << yield(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
ありがとう。