【发布时间】:2012-08-28 09:57:54
【问题描述】:
我希望通过在 1..5 循环中使用 i 将 @comment1 更改为 @comment2。我有以下非常重复的代码。我希望把它干掉。
您好,我正在使用acts_as_commentable_with_threading。我基本上是在遍历所有 cmets 并检查该评论是否有孩子。如果是这样,打印出孩子,同时检查这些孩子是否有孩子。所以我计划深入几个层次,因此@comment1、2、3 等......我怎样才能干燥这个?递归一些如何?如果没有,我可能会更深入一些级别,并在 @comment5 处结束评论缩进。
编辑!
谢谢萨米隆!
这是更新后的辅助函数...
def show_comments_with_children(comments)
comments.each do |comment|
yield comment
if comment.children.any?
concat <<-EOF.html_safe
<div class="span7 offset1-1 pcomment">
EOF
show_comments_with_children(comment.children) { |x| yield x } #Dont worry, this will not run another query :)
concat <<-EOF.html_safe
</div>
EOF
end
end
end
<div class="span7 offset1-1 pcomment">
<% @comment1 = comment.children%>
<% for comment in @comment1 %>
<%= render "comment_replies", :comment => comment %>
<div class="span7 offset1-1 pcomment">
<% @comment2 = comment.children%>
<% for comment in @comment2 %>
<%= render "comment_replies", :comment => comment %>
<div class="span7 offset1-1 pcomment">
<% @comment3 = comment.children%>
<% for comment in @comment3 %>
<%= render "comment_replies", :comment => comment %>
<% end %>
</div>
....
<%(1..5).each do |i| %>
<% @comment1 = comment.children%>
<% for comment in @comment1 %>
<%= render "comment_replies", :comment => comment %>
<% end %>
<% end %>
【问题讨论】:
-
您能否详细说明“
@comment1使用i更改为@comment2”是什么意思? -
我的视图有很多重复的代码,我正试图把它们干掉。我正在打印出带螺纹的 cmets。在我看来,这一直在重复......
-
这是一种代码异味,如果您有一系列用于相同目的的 ivars,则应考虑使用一个哈希或数组。
-
这段代码不是打印了8次吗?
-
可能不是实际代码。
标签: ruby-on-rails ruby string recursion