Sha256: 94ac6caa15af3225e0f0da90812d2488088ce25a32eabdd142d9a2cd1e6c86c5

Contents?: true

Size: 1.12 KB

Versions: 2

Compression:

Stored size: 1.12 KB

Contents

module Mailit
  module Mime
    module_function

    def type_for(filename)
      detect_handler unless defined?(@mime_handler)
      send(@mime_handler, filename)
    end

    def detect_handler
      try_require('rubygems')

      if try_require('mime/types')
        @mime_handler = :from_mime_types
      elsif try_require('rack') and try_require('rack/mime')
        @mime_handler = :from_rack
      else
        require 'webrick/httputils'
        @webrick_types = WEBrick::HTTPUtils::DefaultMimeTypes.dup
        try_extend_webrick('/etc/mime.types')
        @mime_handler = :from_webrick
      end
    end

    def from_mime_types(filename)
      MIME::Types.type_for(filename) || 'application/octet-stream'
    end

    def from_rack(filename)
      Rack::Mime.mime_type(File.extname(filename))
    end

    def from_webrick(filename)
      WEBrick::HTTPUtils.mime_type(filename, @webrick_types)
    end

    def try_extend_webrick(file)
      hash = WEBrick::HTTPUtils.load_mime_types(file)
      @webrick_types.merge!(hash)
    rescue
    end

    def try_require(lib)
      require lib
      true
    rescue LoadError
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
mailit-2011.01.27 lib/mailit/mime.rb
mailit-2010.06.03 lib/mailit/mime.rb