blob: 1ce616cf75a3b99eb431096273a1d9368684d330 (
plain)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
require 'nokogiri'
module AttachmentToHTML
module Adapters
# Convert text/plain documents in to HTML
class Text
attr_reader :attachment, :wrapper
# Public: Initialize a Text converter
#
# attachment - the FoiAttachment to convert to HTML
# opts - a Hash of options (default: {}):
# :wrapper - String id of the div that wraps the
# attachment body
def initialize(attachment, opts = {})
@attachment = attachment
@wrapper = opts.fetch(:wrapper, 'wrapper')
end
# Public: Convert the attachment to HTML
#
# Returns a String
def to_html
@html ||= generate_html
end
# Public: Was the document conversion successful?
#
# Returns a Boolean
def success?
has_content? || contains_images?
end
private
def generate_html
html = "<!DOCTYPE html>"
html += "<html>"
html += "<head>"
html += "<title>#{ title }</title>"
html += "</head>"
html += "<body>"
html += "<div id=\"#{ wrapper }\">"
html += "<div id=\"view-html-content\">"
html += body
html += "</div>"
html += "</div>"
html += "</body>"
html += "</html>"
end
def title
@title ||= attachment.display_filename
end
def body
text = attachment.body.strip
text = CGI.escapeHTML(text)
text = MySociety::Format.make_clickable(text)
text = text.gsub(/\n/, '<br>')
end
# Does the body element have any content, excluding HTML tags?
#
# Returns a Boolean
def has_content?
!parsed.css('body').inner_text.empty?
end
def contains_images?
parsed.css('body img').any?
end
# Parse the output of to_html to check for success
#
# Returns a Nokogiri::HTML::Document
def parsed
@parsed ||= Nokogiri::HTML.parse(to_html)
end
end
end
end
|