49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
|
# File 'lib/html_email_creator/processor.rb', line 49
def to_plain_text
return @processed_plain_text_email if @processed_plain_text_email
doc = Nokogiri::HTML(to_html)
doc.css('style').each { |node| node.remove }
doc.css('title').each { |node| node.remove }
doc.css('script').each { |node| node.remove }
doc.css('link').each { |node| node.remove }
doc.css('a').each do |node|
img = node.at_css('img')
node.content = if img
"#{img['alt']} (#{node['href']})"
else
"#{node.content} (#{node['href']})"
end
end
doc.css('img').each do |node|
node.content = "#{node['alt']} (#{node['src']})"
end
doc.css('strong').each do |node|
node.content = "*#{node.content}*"
end
doc.css('li').each { |node| node.content = "- #{node.content.strip}" }
doc.css('div.h1 div').each do |node|
node.content = "\n#{'=' * 77}\n#{node.content}"
end
doc.css('div.h2 div').each do |node|
node.content = "\n#{'-' * 77}\n#{node.content}"
end
doc.css('div.h3 div').each do |node|
node.content = "\n#{'- ' * 39}\n#{node.content}"
end
doc.css('div.h4 div').each do |node|
node.content = "\n#{node.content}"
end
doc.css('p').each do |node|
node.content = "\n#{node.content}"
end
doc.css('table.inline').each do |table|
content = []
table.css('tr').each do |row|
i = 0
row.css('td').each do |column|
empty_column = column.content.strip.gsub(/^\p{Space}+|\p{Space}+$/, "").empty?
if content[i]
content[i] = content[i] + "\n* #{column.content}" unless empty_column
else
content[i] = "\n#{column.content}" unless empty_column
end
i = i + 1
end
end
table.content = "#{content.join("\n")}\n"
end
previous = ""
@processed_plain_text_email = doc.css('body').text.split("\n").map do |line|
res = line.gsub(/^\p{Space}+|\p{Space}+$/, "")
new_previous = res
res = nil if res.empty? && previous.empty?
previous = new_previous
res
end.compact.join("\n")
end
|