aboutsummaryrefslogtreecommitdiffstats
path: root/lib/attachment_to_html/attachment_to_html.rb
diff options
context:
space:
mode:
authorGareth Rees <gareth@mysociety.org>2014-03-17 11:15:40 +0000
committerGareth Rees <gareth@mysociety.org>2014-03-28 09:39:04 +0000
commitd57ca2a22579df4c634d554989c0ee9e4ebb5165 (patch)
treee1d11c626cedf57373be95b6b1ec6ce4dc22ea30 /lib/attachment_to_html/attachment_to_html.rb
parent0adf9399cbef42054809479c8f1b64dad7bbf8ca (diff)
Add AttachmentToHTML library
Extracts the attachment processing from FoiAttachment#body_to_html AttachmentToHTML contains adapters which convert - text/plain - application/pdf - application/rtf Results are returned as an AttachmentHTML::HTML instance which contains the raw HTML and other metadata about the conversion.
Diffstat (limited to 'lib/attachment_to_html/attachment_to_html.rb')
-rw-r--r--lib/attachment_to_html/attachment_to_html.rb41
1 files changed, 41 insertions, 0 deletions
diff --git a/lib/attachment_to_html/attachment_to_html.rb b/lib/attachment_to_html/attachment_to_html.rb
new file mode 100644
index 000000000..5f63661b4
--- /dev/null
+++ b/lib/attachment_to_html/attachment_to_html.rb
@@ -0,0 +1,41 @@
+require 'html'
+
+Dir[File.dirname(__FILE__) + '/adapters/*.rb'].each do |file|
+ require file
+end
+
+module AttachmentToHTML
+ extend self
+
+ def to_html(attachment, opts = {})
+ adapter = adapter_for(attachment).new(attachment, opts)
+ html = HTML.new(adapter)
+
+ if html.success?
+ html
+ else
+ fallback = fallback_adapter_for(attachment).new(attachment, opts)
+ HTML.new(fallback)
+ end
+ end
+
+ private
+
+ def adapter_for(attachment)
+ case attachment.content_type
+ when 'text/plain' then Adapters::Text
+ when 'application/pdf' then Adapters::PDF
+ when 'application/rtf' then Adapters::RTF
+ else
+ fallback_adapter_for(attachment)
+ end
+ end
+
+ def fallback_adapter_for(attachment)
+ if attachment.has_google_docs_viewer?
+ Adapters::GoogleDocsViewer
+ else
+ Adapters::CouldNotConvert
+ end
+ end
+end