Sha256: 170209883803a137e4ddbb2402c114afc47638db748d075a86899ebbbe8c883f
Contents?: true
Size: 1.8 KB
Versions: 1
Compression:
Stored size: 1.8 KB
Contents
module TruncateHtml class HtmlTruncator def initialize(original_html) @original_html = original_html end def truncate(options = {}) length = options[:length] || TruncateHtml.configuration.length @omission = options[:omission] || TruncateHtml.configuration.omission @word_boundry = (options.has_key?(:word_boundry) ? options[:word_boundry] : TruncateHtml.configuration.word_boundry) @chars_remaining = length - @omission.length @open_tags, @truncated_html = [], [''] @original_html.html_tokens.each do |token| #if truncate_more?(token) if @chars_remaining > 0 process_token(token) else close_open_tags break end end @truncated_html.join end private def process_token(token) append_to_result(token) if token.html_tag? if token.open_tag? @open_tags << token else remove_latest_open_tag(token) end else @chars_remaining -= (@word_boundry ? token.length : token[0, @chars_remaining].length) end end def append_to_result(token) if @word_boundry @truncated_html << token else @truncated_html << token[0, @chars_remaining] end end def close_open_tags @truncated_html[-1] = @truncated_html[-1].rstrip + @omission @open_tags.reverse_each do |open_tag| @truncated_html << open_tag.matching_close_tag end end def remove_latest_open_tag(close_tag) (0...@open_tags.length).to_a.reverse.each do |index| if @open_tags[index].matching_close_tag == close_tag @open_tags.delete_at(index) break end end end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
truncate_html-0.3.0 | lib/truncate_html/html_truncator.rb |