Module: TruncateHTML

Defined in:
lib/truncateHTML.rb

Class Method Summary collapse

Class Method Details

.truncate(text, options = {}) ⇒ Object

Like the Rails truncate helper but doesn’t break HTML tags, entities, and optionally words.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/truncateHTML.rb', line 27

def self.truncate(text, options={})
  return if text.nil?

  max_length = options[:max_length] || 40
  ellipsis = options[:ellipsis] || "..."
  words = options[:words] || false
  status = options[:status] || false
  # use :link => link_to('more', post_path), or something to that effect

  doc = Hpricot(text.to_s)
  ellipsis_length = Hpricot(ellipsis).inner_text.length
  content_length = doc.inner_text.length
  actual_length = max_length - ellipsis_length

  if content_length > max_length
    truncated_doc = doc.truncate(actual_length)

    if words
      word_length = actual_length - (truncated_doc.inner_html.length - truncated_doc.inner_html.rindex(' '))
      truncated_doc = doc.truncate(word_length)
    end

    #XXX The check here has to be blank as the inner_html for text node is blank
    return_string = truncated_doc.inner_html + ellipsis
    return_string += options[:link] if options[:link]
    return_status = true
  else
    return_string = text.to_s
    return_status = false
  end

  return status ? [return_string, return_status] : return_string
end