From 888e68a1637ca784a7bf51a6bbb524dcf7413b13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9gis=20Hanol?= Date: Tue, 7 May 2019 17:35:52 +0200 Subject: [PATCH] FIX: When mutating a string to build a diff. Duplicate it first Co-authored-by: Roman Rizzi --- lib/discourse_diff.rb | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/lib/discourse_diff.rb b/lib/discourse_diff.rb index 8126b87b37e19..041a71306a8a6 100644 --- a/lib/discourse_diff.rb +++ b/lib/discourse_diff.rb @@ -178,24 +178,25 @@ def tokenize_html(html) end def add_class_or_wrap_in_tags(html_or_text, klass) - index_of_next_chevron = html_or_text.index(">") - if html_or_text.length > 0 && html_or_text[0] == '<' && index_of_next_chevron - index_of_class = html_or_text.index("class=") + result = html_or_text.dup + index_of_next_chevron = result.index(">") + if result.length > 0 && result[0] == '<' && index_of_next_chevron + index_of_class = result.index("class=") if index_of_class.nil? || index_of_class > index_of_next_chevron # we do not have a class for the current tag # add it right before the ">" - html_or_text.insert(index_of_next_chevron, " class=\"diff-#{klass}\"") + result.insert(index_of_next_chevron, " class=\"diff-#{klass}\"") else # we have a class, insert it at the beginning if not already present - classes = html_or_text[/class=(["'])([^\1]*)\1/, 2] + classes = result[/class=(["'])([^\1]*)\1/, 2] if classes.include?("diff-#{klass}") - html_or_text + result else - html_or_text.insert(index_of_class + "class=".length + 1, "diff-#{klass} ") + result.insert(index_of_class + "class=".length + 1, "diff-#{klass} ") end end else - "<#{klass}>#{html_or_text}" + "<#{klass}>#{result}" end end