diff --git a/lib/truncate_html/html_truncator.rb b/lib/truncate_html/html_truncator.rb
index 52b707f..a08de0c 100644
--- a/lib/truncate_html/html_truncator.rb
+++ b/lib/truncate_html/html_truncator.rb
@@ -14,7 +14,7 @@ def initialize(original_html, options = {})
def truncate
return @omission if @chars_remaining < 0
@original_html.html_tokens.each do |token|
- if @chars_remaining <= 0 || truncate_token?(token)
+ if @chars_remaining <= 0
close_open_tags
break
else
@@ -50,7 +50,7 @@ def build_output
def process_token(token)
append_to_result(token)
- if token.html_tag?
+ if token.html_tag? && @chars_remaining > 0
if token.open_tag?
@open_tags << token
else
@@ -58,14 +58,17 @@ def process_token(token)
end
elsif !token.html_comment?
@chars_remaining -= (@word_boundary ? token.length : token[0, @chars_remaining].length)
- if @chars_remaining <= 0
- @truncated_html[-1] = @truncated_html[-1].rstrip + @omission
- end
+ end
+
+ if @chars_remaining <= 0
+ @truncated_html[-1] = @truncated_html[-1].rstrip + @omission
end
end
def append_to_result(token)
- if token.html_tag? || token.html_comment?
+ if truncate_token?(token)
+ @chars_remaining = 0
+ elsif token.html_tag? || token.html_comment?
@truncated_html << token
elsif @word_boundary
@truncated_html << token if (@chars_remaining - token.length) >= 0
diff --git a/spec/truncate_html/html_truncator_spec.rb b/spec/truncate_html/html_truncator_spec.rb
index 0da14d6..b4b6c11 100644
--- a/spec/truncate_html/html_truncator_spec.rb
+++ b/spec/truncate_html/html_truncator_spec.rb
@@ -158,7 +158,7 @@ def truncate(html, opts = {})
truncate('This is line one. This is line two.', :length => 30, :break_token => '').should == 'This is line one. This is...'
end
it 'truncates before the length param if the break_token is before the token at "length"' do
- truncate('This is line one. This is line two.', :length => 30, :break_token => '').should == 'This is line one.'
+ truncate('This is line one. This is line two.', :length => 30, :break_token => '').should == 'This is line one....'
end
end
@@ -170,7 +170,7 @@ def truncate(html, opts = {})
truncate('This is line one. This is line two.', :length => 30, :break_token => '').should == 'This is line one. This is...'
end
it 'truncates before the length param if the break_token is before the token at "length"' do
- truncate('This is line one. This is line two.', :length => 30, :break_token => '').should == 'This is line one.'
+ truncate('This is line one. This is line two.', :length => 30, :break_token => '').should == 'This is line one....'
end
end
@@ -182,7 +182,7 @@ def truncate(html, opts = {})
truncate('This is line one. This is line