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) ⇒ HtmlTruncator

Returns a new instance of HtmlTruncator.



4
5
6
# File 'lib/truncate_html/html_truncator.rb', line 4

def initialize(original_html)
  @original_html  = original_html
end

Instance Method Details

#truncate(options = {}) ⇒ Object



8
9
10
11
12
13
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 8

def truncate(options = {})
  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)
  @chars_remaining = length - @omission.length
  @open_tags, @truncated_html = [], ['']

  return @omission if @chars_remaining < 0
  @original_html.html_tokens.each do |token|
    if @chars_remaining > 0
      process_token(token)
    else
      close_open_tags
      break
    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