I would like the @comment1 to change to @comment2 by using the i in the 1..5 loop. I have the following code that is pretty repetitive. I am hoping to dry it up.
Hi,I am using acts_as_commentable_with_threading. I am basically looping through all comments and checking to see if that comment has children. If so, print out the children while checking to see if those children have children. So I plan on going a few levels deep, hence the @comment1,2,3, etc…How can I DRY this? Recursion some how? If not, I could maybe go a few levels deep and end the comment indentation at @comment5 for example.
EDIT!
Thank you Samiron!
Here is the updated helper function…
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 %>
Probably you are looking for
instance_variable_set.But definitely this is not a recommendable approach. You can share your controller code and what you want to achieve in your view. There must be some way to make it properly DRY. In your post you are always getting
comment.children. is it really?Actual Solution:
Your view code will be like this
and add this helper function
show_comments_with_childrenin your helper function. Which will be.