forked from MattHall/truncatehtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
html_filters.rb
67 lines (52 loc) · 1.49 KB
/
html_filters.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# encoding: utf-8
require 'rubygems'
require 'nokogiri'
module Liquid
module StandardFilters
def truncatehtml(raw, max_length = 15, continuation_string = "...")
doc = Nokogiri::HTML(Iconv.conv('UTF8//TRANSLIT//IGNORE', 'UTF8', raw))
current_length = 0;
deleting = false
to_delete = []
depth_first(doc.children.first) do |node|
if !deleting && node.class == Nokogiri::XML::Text
current_length += node.text.length
end
if deleting
to_delete << node
end
if !deleting && current_length > max_length
deleting = true
trim_to_length = current_length - max_length + 1
node.content = node.text[0..trim_to_length] + continuation_string
end
end
to_delete.map(&:remove)
doc.inner_html
end
private
def depth_first(root, &block)
parent = root.parent
sibling = root.next
first_child = root.children.first
yield(root)
if first_child
depth_first(first_child, &block)
else
if sibling
depth_first(sibling, &block)
else
# back up to the next sibling
n = parent
while n && n.next.nil? && n.name != "document"
n = n.parent
end
# To the sibling - otherwise, we're done!
if n && n.next
depth_first(n.next, &block)
end
end
end
end
end
end