module Rid module Attachments # Mime type mapping from extensions MIME_TYPE_MAPPING = { ".html" => "text/html", ".js" => "text/javascript", ".css" => "text/css", } # encode attachments and add meta data # def map_attachments! return if attachments.empty? doc = {} attachments.flatten.each do |key, value| doc[key] = { "data" => encode_attachment(value), "content_type" => mime_type_for(key) } end self.attachments = doc end # decode attachments and flatten meta data hash # def reduce_attachments! return if attachments.empty? doc = {} attachments.each do |key, value| data = value["data"] next unless data doc[key] = decode_attachment(data) end self.attachments = doc end private # accessor for attachments hash # def attachments hash["_attachments"] || {} end def attachments=(value) self.hash["_attachments"] = value end def decode_attachment(data) data.unpack("m").first end def encode_attachment(data) [data].pack("m").gsub(/\s+/,'') end def mime_type_for(filename) ext = File.extname(filename) MIME_TYPE_MAPPING[ext] || 'text/plain' end end end