Module: Refinery::HtmlTruncationHelper

Included in:
ApplicationHelper
Defined in:
vendor/plugins/refinery/lib/refinery/html_truncation_helper.rb

Instance Method Summary collapse

Instance Method Details

#truncate(text, *args) ⇒ 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
60
61
62
63
64
65
66
67
68
# File 'vendor/plugins/refinery/lib/refinery/html_truncation_helper.rb', line 27

def truncate(text, *args)
  return super unless ((arguments = args.dup).extract_options![:preserve_html_tags] == true) # don't ruin the current args object
  return if text.nil?

  options = args.extract_options!
  max_length = options[:length] || 30
  omission = options[:omission] || "..."
  # use :link => link_to('more', post_path), or something to that effect

  doc = Hpricot(text.to_s)
  omission_length = Hpricot(omission).inner_text.mb_chars.length
  content_length = doc.inner_text.mb_chars.length
  actual_length = max_length - omission_length

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

    if (options[:preserve_full_words] || false)
      word_length = actual_length - (truncated_doc.inner_html.mb_chars.length - truncated_doc.inner_html.rindex(' '))
      truncated_doc = doc.truncate(word_length)
    end
    if (last_child = truncated_doc.children.last).inner_html.nil?
      "#{truncated_doc.inner_html}#{omission}#{options[:link]}" if options[:link]
    else
      last_child.inner_html = "#{last_child.inner_html.gsub(/\W.[^\s]+$/, "")}#{omission}"
      last_child.inner_html += options[:link] if options[:link]
      truncated_doc
    end
  else
    if options[:link]
      last_child = doc.children.last
      if last_child.inner_html.nil?
        doc.inner_html + options[:link]
      else
        last_child.inner_html = last_child.inner_html.gsub(/\W.[^\s]+$/, "") + options[:link]
        doc
      end
    else
      text.to_s
    end
  end
end