Module: Postablr::TruncateHtmlHelper

Defined in:
app/helpers/postablr/truncate_html_helper.rb

Instance Method Summary collapse

Instance Method Details

#truncate_html(text, max_length = 10, ellipsis = "...") ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'app/helpers/postablr/truncate_html_helper.rb', line 7

def truncate_html(text, max_length = 10, ellipsis = "...")
  doc = Nokogiri::HTML::DocumentFragment.parse text
  # remove syntax highlighting
  doc.css("div.CodeRay").each do |node|
    node.remove
  end
  content_length = doc.inner_text.length
  if content_length > max_length
    doc = doc.truncate(max_length)
    more = Nokogiri::HTML::DocumentFragment.parse ellipsis
    doc.children.last.add_child(more.children)
    doc.to_html.html_safe
  else
    text.to_s
  end
end