Sha256: 800e40fe9023ca95ca22558cf39d3f7b6a0d1be72a8f349d5258bd439a22cb8e

Contents?: true

Size: 1.31 KB

Versions: 6

Compression:

Stored size: 1.31 KB

Contents

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

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rid-0.5.2 lib/rid/attachments.rb
rid-0.5.1 lib/rid/attachments.rb
rid-0.5.0 lib/rid/attachments.rb
rid-0.4.1 lib/rid/attachments.rb
rid-0.4.0 lib/rid/attachments.rb
rid-0.3.1 lib/rid/attachments.rb