Skip to content

Commit 66abb5b

Browse files
committed
Fix a big with html entities
1 parent e0b2093 commit 66abb5b

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

lib/html_truncator.rb

+11-4
Original file line numberDiff line numberDiff line change
@@ -72,18 +72,25 @@ def self_closing?
7272

7373
class Nokogiri::XML::Text
7474
def truncate(max, opts)
75-
words = to_xhtml.scan(/\s*\S+/)
7675
if opts[:length_in_chars]
77-
count = to_xhtml.length
76+
count = content.length
7877
return [to_xhtml, count, opts] if count <= max && max > 0
78+
words = content.scan(/\s*\S+/)
7979
if words.size > 1
8080
words.inject('') do |string, word|
81-
return [string, count, opts] if string.length + word.length > max
81+
if string.length + word.length > max
82+
txt = dup
83+
txt.content = string
84+
return [txt.to_xhtml, count, opts]
85+
end
8286
string + word
8387
end
8488
end
85-
[content.slice(0, max), count, opts]
89+
txt = dup
90+
txt.content = content.slice(0, max)
91+
[txt.to_xhtml, count, opts]
8692
else
93+
words = to_xhtml.scan(/\s*\S+/)
8794
count = words.length
8895
return [to_xhtml, count, opts] if count <= max && max > 0
8996
[words.slice(0, max).join, count, opts]

spec/html_truncator_spec.rb

+8
Original file line numberDiff line numberDiff line change
@@ -163,4 +163,12 @@
163163
it "should remove punctuation before the ellipsis" do
164164
HTML_Truncator.truncate(short_text, 1).should == "<p>Foo…</p>"
165165
end
166+
167+
it "should behave correctly with html entities" do
168+
HTML_Truncator.truncate("<br>&lt;br&gt;123456789012", 9, length_in_chars: true).should == "<br>&lt;br&gt;12345…"
169+
HTML_Truncator.truncate("<p>&lt;br&gt; 1</p>2 3456789", 9, length_in_chars: true).should == "<p>&lt;br&gt; 1</p>2…"
170+
HTML_Truncator.truncate("&lt;br&gt;", 10, length_in_chars: true).should == "&lt;br&gt;"
171+
HTML_Truncator.truncate("<br>12345678901", 10, length_in_chars: true).should == "<br>1234567890…"
172+
HTML_Truncator.truncate("<br>&lt;br&gt; 1 2 3", 2).should == "<br>&lt;br&gt; 1…"
173+
end
166174
end

0 commit comments

Comments
 (0)