【发布时间】:2010-08-29 04:59:16
【问题描述】:
你会如何重构这个逻辑填充部分?
<%- for post in @posts -%>
<div class="post">
<%= link_to post.title, post %>
<%- if post.name.empty? -%>
<%- else -%>
<span class="name">
by
<%- if post.email.blank? -%>
<%= post.name %>
<%- else -%>
<a href="mailto:<%= post.email %>"><%= post.name %></a>
<%- end -%>
</span>
<%- end -%>
<span class="time">
active   <%= timeago(post.updated_at) %>
</span>
<%- if post.comments.empty? -%>
<span class="reply">
<%= link_to 'reply', :controller => 'posts', :action => 'show', :id => post %>
</span>
<% else %>
<span class="reply">
<%= link_to pluralize(post.comments.count, 'reply'), :controller => 'posts', :action => 'show', :id => post %>
</span>
<%- end -%>
<p><%= sanitize post.content,
:tags => %w(a embed img object p param),
:attributes => %w(allowfullscreen allowscriptaccess href name src type value) %></p>
<%- unless controller.controller_name == "tags" -%>
<%- unless post.tag_list.nil? || post.tag_list.empty? -%>
<%- post.tags.each do |t| -%>
<div class="tag"><%= link_to t.name.titleize, tag_path(t) %></div>
<%- end -%>
<%- end -%>
<%- end -%>
<%- unless post.comments.empty? -%>
<div class="comments">
<%= render :partial => post.firstcomments %>
<%- if post.comments.count >= 4 -%>
<%= link_to 'more...', :action => 'show', :id => message %>
<%- end -%>
</div>
<%- end -%>
</div>
<%- end -%>
注意事项: post.firstcmets 只返回 3 个最新帖子。 使用 Rails 3 和 Ruby 1.9.2。 我没有查看代码的清理部分,我意识到 Rails 3 默认会转义所有内容,因此现在可以安全地忽略它,除非有人知道如何转换它。
我的模型很干净,我的控制器很不错,但这个部分很糟糕。它完成了它需要做的事情,但在刷新页面时会占用大部分渲染时间。非常感谢评论、建议和代码。感谢您阅读我的问题。
【问题讨论】:
标签: ruby-on-rails refactoring ruby-on-rails-3 partial-views