Module: EffectiveTruncateHtmlHelper

Defined in:
app/helpers/effective_truncate_html_helper.rb

Overview

Instance Method Summary collapse

Instance Method Details

#chunk_html(text, max_length = 2, _ellipsis = '...', read_more = nil) ⇒ Object



5
6
7
8
9
10
11
12
13
14
# File 'app/helpers/effective_truncate_html_helper.rb', line 5

def chunk_html(text, max_length = 2, _ellipsis = '...', read_more = nil)
  doc = Nokogiri::HTML::DocumentFragment.parse text

  if doc.children.length >= max_length
    doc.children.last.remove while doc.children.length > max_length
    doc.children.last.add_next_sibling Nokogiri::HTML::DocumentFragment.parse("<p>#{ read_more }</p>")
  end

  doc.inner_html.html_safe
end

#truncate_html(text, max_length = 200, ellipsis = '...', read_more = nil) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'app/helpers/effective_truncate_html_helper.rb', line 16

def truncate_html(text, max_length = 200, ellipsis = '...', read_more = nil)
  ellipsis_length = ellipsis.to_s.length
  doc = Nokogiri::HTML::DocumentFragment.parse text
  content_length = doc.inner_text.length
  actual_length = max_length - ellipsis_length

  if content_length > actual_length
    truncated_node = doc.truncate_html(actual_length)

    last_node = truncated_node
    while last_node.respond_to?(:children) && last_node.children.present?
      last_node = last_node.children.reverse.find { |node| node.try(:name) != 'a' } # Find the last non-A node
    end

    if read_more.present?
      read_more_node = Nokogiri::HTML::DocumentFragment.parse(read_more.to_s)
      last_node.add_next_sibling(read_more_node)
    end

    if ellipsis.present?
      ellipsis_node = Nokogiri::XML::Text.new(ellipsis.to_s, doc)
      last_node.add_next_sibling(ellipsis_node)
    end

    truncated_node.inner_html
  else
    text.to_s
  end.html_safe
end