From 97bbb6a5d5e02509a2ff863e044975a86a4afcdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Strachota?= Date: Fri, 5 Jan 2024 09:36:04 +0100 Subject: [PATCH] Fix punctuation removal for strings with new line characters The regexp for substitution of the punctuation chars matched with end of line instead if end of the string. That caused the punctuation being removed from the middle of the text when it was followed by a new line. --- lib/html_truncator.rb | 2 +- spec/html_truncator_spec.rb | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/html_truncator.rb b/lib/html_truncator.rb index 85084d7..37d2a11 100644 --- a/lib/html_truncator.rb +++ b/lib/html_truncator.rb @@ -51,7 +51,7 @@ def inner_truncate(max, opts) inner += txt next if remaining >= 0 if ellipsable? - r = %r/[\s#{HTML_Truncator.punctuation_chars.join}]+$/ + r = %r/[\s#{HTML_Truncator.punctuation_chars.join}]+\Z/ inner = inner.sub(r, '') + opts[:ellipsis] opts[:ellipsis] = "" opts[:was_truncated] = true diff --git a/spec/html_truncator_spec.rb b/spec/html_truncator_spec.rb index 1099c40..9a1a7bf 100644 --- a/spec/html_truncator_spec.rb +++ b/spec/html_truncator_spec.rb @@ -14,6 +14,7 @@ let(:short_text) { "

Foo! Bar Baz

" } let(:long_text) { "

Foo " + ("Bar Baz " * 100) + "Quux

" } let(:list_text) { "

Foo:

" } + let(:text_with_new_lines) { "

Foo.\n Bar.\n Baz.

" } it "should not modify short text" do HTML_Truncator.truncate(short_text, 10).should == short_text @@ -162,6 +163,7 @@ it "should remove punctuation before the ellipsis" do HTML_Truncator.truncate(short_text, 1).should == "

Foo…

" + HTML_Truncator.truncate(text_with_new_lines, 12, :length_in_chars => true).should == "

Foo.\n Bar…

" end it "should behave correctly with html entities" do