module Rid module Attachments # Mime type mapping from extensions MIME_TYPE_MAPPING = { ".html" => "text/html", ".js" => "text/javascript", ".css" => "text/css", } def reduce_attachments! return hash unless hash["_attachments"] attachments = {} hash["_attachments"].each do |key, value| data = value["data"] next unless data attachments.update key => decode_attachment(data) end hash.update "_attachments" => attachments end def map_attachments! return unless hash["_attachments"] attachments = {} flatten_attachements(hash["_attachments"]).each do |key, value| attachments.update key => { "data" => encode_attachment(value), "content_type" => mime_type_for(key) } end self.hash.update "_attachments" => attachments end def flatten_attachements(doc, base = nil) result = {} doc.each do |key, value| new_base = base ? [base, key].join('/') : key if value.is_a?(Hash) result.update flatten_attachements(value, new_base) else result.update new_base => value end end result 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