Class: TruncateHtml::HtmlTruncator

Inherits:
Object
  • Object
show all
Defined in:
lib/truncate_html/html_truncator.rb

Instance Method Summary collapse

Constructor Details

#initialize(original_html, options = {}) ⇒ HtmlTruncator

Returns a new instance of HtmlTruncator.



4
5
6
7
8
9
10
11
12
# File 'lib/truncate_html/html_truncator.rb', line 4

def initialize(original_html, options = {})
  @original_html   = original_html
  length           = options[:length]       || TruncateHtml.configuration.length
  @omission        = options[:omission]     || TruncateHtml.configuration.omission
  @word_boundary   = (options.has_key?(:word_boundary) ? options[:word_boundary] : TruncateHtml.configuration.word_boundary)
  @break_token     = options[:break_token] || TruncateHtml.configuration.break_token || nil
  @chars_remaining = length - @omission.length
  @open_tags, @truncated_html = [], ['']
end

Instance Method Details

#truncateObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/truncate_html/html_truncator.rb', line 14

def truncate
  return @omission if @chars_remaining < 0
  @original_html.html_tokens.each do |token|
    if @chars_remaining <= 0 || truncate_token?(token)
      close_open_tags
      break
    else
      process_token(token)
    end
  end

  out = @truncated_html.join

  if word_boundary
    term_regexp = Regexp.new("^.*#{word_boundary.source}")
    match = out.match(term_regexp)
    match ? match[0] : out
  else
    out
  end
end