aboutsummaryrefslogtreecommitdiffstats
path: root/lib/attachment_to_html/adapters/text.rb
blob: e99183f0ed7d49e7104032b2d6abc63af231900d (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
module AttachmentToHTML
    module Adapters
        # Convert text/plain documents in to HTML
        class Text

            attr_reader :attachment

            # Public: Initialize a Text converter
            #
            # attachment - the FoiAttachment to convert to HTML
            # opts       - a Hash of options (default: {}):
            #              No options currently accepted
            def initialize(attachment, opts = {})
                @attachment = attachment
            end

            # Public: The title to use in the <title> tag
            #
            # Returns a String
            def title
                @title ||= attachment.display_filename
            end

            # Public: The contents of the extracted html <body> tag
            #
            # Returns a String
            def body
                @body ||= parse_body
            end

            # Public: Was the document conversion successful?
            #
            # Returns a Boolean
            def success?
                has_content? || contains_images?
            end

            private

            def convert
                text = attachment.body.strip
                text = CGI.escapeHTML(text)
                text = MySociety::Format.make_clickable(text)
                text = text.gsub(/\n/, '<br>')
            end

            def parse_body
                convert
            end

            def has_content?
                !body.gsub(/\s+/,"").gsub(/\<[^\>]*\>/, "").empty?
            end

            def contains_images?
                body.match(/<img[^>]*>/mi) ? true : false
            end

         end
    end
end