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|
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
|