我需要有关DRYing视图代码的最佳实践的建议.我的应用程序中有三个类(NewsItem,RssItem和BlogItem),它们使用不同的视图,但其中包含类似的部分.其中一个部分是这样的:
<% if current_user %>
<footer>
<%= marks_bar(@item) %>
<%= favorite_button(@item, "blog_item") || delete_from_favorite_button(@item, "blog_item") %>
<%= share_button(@item) %>
<% if current_user.is_mine?(@item) %>
<div><%= link_to "Edit", edit_user_blog_item_path(current_user, @item) %></div>
<% end %>
</footer>
<% end %>
Run Code Online (Sandbox Code Playgroud)
这三个班级几乎相同,所以我决定把它带到一个不同的地方.在这里我很困惑:我应该使用部分或辅助方法吗?我知道帮助程序主要用于从HTML中分离ruby代码,但在这种情况下,帮助程序将如下所示:
def toolbar_for(item, type_str, edit_path)
if current_user
content_tag(:footer) do |b|
marks_bar(item).to_s <<
(delete_from_favorite_button(item, type_str) || favorite_button(@item, type_str)).to_s <<
share_button(@item).to_s <<
(content_tag(:div) { link_to("Edit", edit_path)} if current_user.is_mine?(@item)).to_s
end
end
end
Run Code Online (Sandbox Code Playgroud)
所以,这里几乎没有HTML代码.
你能不能给我一些建议,你认为哪种方法更好,为什么?此外,这些方法中是否存在一些性能问题(例如,多个字符串串联或频繁的部分加载可能代价高昂)?(这个应用程序相当高负载)