Recursive function in helper method scoping issues
Ok so I'm playing around with a nested comments system on rails using Awesome nested set. I'm currently implementing a recursive function to get the nesting working (I know for performance this is terribly inefficient, but I just want this to work before I tune for performance).
So in my application controller I have something like this (building html):
def create_comments_list(comment, commentlist)
commentlist += "<div class=\"comment\" style=\"padding-left:20px;\"><div style=\"display:none;\" class=\"parent_id\">#{comment.id}</div>#{comment.user.name}:<br/><div class=\"ccontent\">#{comment.content}</div><br/><a href=\"#reply\" class=\"reply\" style=\"color:black;\">Reply</a>";
children = comment.children
children.each do |c|
create_comments_list(c, commentlist)
end
commentlist += "</div><div class=\"shortdivider\"> </div>"
commentlist
end
And I invoke in the controller like this:
@commentlist = crea开发者_JAVA技巧te_comments_list(c, @commentlist)
It seems to be doing the full recursion... however in the case of 1 parent comment and 1 child comment the commentlist only spits out the parent comment. If I log things I can see that the child is indeed being appended to the @commentlist inside the recursive call, but when it unwinds to where the parent entered the recursion the commentlist variable no longer contains the child. It appears I don't understand the scoping of these variables... I need commentlist to retain its value after it unwinds from the inner recursion call. Anyone able to shed some light? (Or some better ways of doing this? My bad style bell is going off in my head)
Use the shovel operator <<
instead of +=
if you want to mutate your commentslist
argument.
+=
creates a new string object and assigns it to your variable, but the functions further up in the stack still have the reference to the older string value. <<
changes the existing string object.
a = "foo" # => "foo"
a.object_id # => 69847780
a += "bar" # => "foobar"
a.object_id # => 69786550 (note this is not the same object as before)
b = "foo" # => "foo"
b.object_id # => 69764530
b << "bar" # => "foobar"
b.object_id # => 69764530
精彩评论