Module: HpricotTruncator::NodeWithChildren

Defined in:
lib/truncateHTML/hpricot_truncator.rb

Instance Method Summary collapse

Instance Method Details

#truncate(max_length) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/truncateHTML/hpricot_truncator.rb', line 3

def truncate(max_length)
  return self if inner_text.length <= max_length
  truncated_node = if self.is_a?(Hpricot::Doc)
    self.dup
  else
    self.class.send(:new, self.name, self.attributes)
  end
  truncated_node.children = []
  each_child do |node|
    if node.is_a?(Hpricot::Elem) && node.name == "html"
      node.children.each do |c|
        # Find the body node and use it. Let us reset earlier truncations
        # and start afresh with this body tag
        return c.truncate(max_length) if (c.is_a?(Hpricot::Elem) && c.name == "body")
      end
    end

    remaining_length = max_length - truncated_node.inner_text.length
    break if remaining_length <= 0
    truncated_node.children << node.truncate(remaining_length)
  end
  truncated_node
end