class MIME::Types

MIME::Types is a registry of MIME types. It is both a class (created with ::new) and a default registry (loaded automatically or through interactions with #[] and #type_for).

The Default mime-types Registry

The default mime-types registry is loaded automatically when the library is required (require 'mime/types'), but it may be lazily loaded (loaded on first use) with the use of the environment variable RUBY_MIME_TYPES_LAZY_LOAD having any value other than false. The initial startup is about 14× faster (~10 ms vs ~140 ms), but the registry will be loaded at some point in the future.

The default mime-types registry can also be loaded from a Marshal cache file specific to the version of MIME::Types being loaded. This will be handled automatically with the use of a file referred to in the environment variable RUBY_MIME_TYPES_CACHE. MIME::Types will attempt to load the registry from this cache file (MIME::Type::Cache.load); if it cannot be loaded (because the file does not exist, there is an error, or the data is for a different version of mime-types), the default registry will be loaded from the normal JSON version and then the cache file will be written to the location indicated by RUBY_MIME_TYPES_CACHE. Cache file loads just over 4½× faster (~30 ms vs ~140 ms). loads.



require 'mime/types'

plaintext = MIME::Types['text/plain']
print plaintext.media_type           # => 'text'
print plaintext.sub_type             # => 'plain'

puts plaintext.extensions.join(" ")  # => 'asc txt c cc h hh cpp'

puts plaintext.encoding              # => 8bit
puts plaintext.binary?               # => false
puts plaintext.ascii?                # => true
puts plaintext.obsolete?             # => false
puts plaintext.registered?           # => true
puts plaintext == 'text/plain'       # => true
puts MIME::Type.simplified('x-appl/x-zip') # => 'appl/zip'



Caching of MIME::Types registries is advisable if you will be loading the default registry relatively frequently. With the class methods on MIME::Types::Cache, any MIME::Types registry can be marshaled quickly and easily.

The cache is invalidated on a per-version basis; a cache file for version 2.0 will not be reused with version 2.0.1.


The release version of Ruby MIME::Types



The data version.

Public Class Methods

new() click to toggle source

Creates a new MIME::Types registry.

# File lib/mime/types.rb, line 71
def initialize
  @type_variants    =
  @extension_index  =
  @data_version     = VERSION.dup.freeze

Public Instance Methods

[](type_id, flags = {}) click to toggle source

Returns a list of MIME::Type objects, which may be empty. The optional flag parameters are :complete (finds only complete MIME::Type objects) and :registered (finds only MIME::Types that are registered). It is possible for multiple matches to be returned for either type (in the example below, ‘text/plain’ returns two values – one for the general case, and one for VMS systems).

puts "\nMIME::Types['text/plain']"
MIME::Types['text/plain'].each { |t| puts t.to_a.join(", ") }

puts "\nMIME::Types[/^image/, complete: true]"
MIME::Types[/^image/, :complete => true].each do |t|
  puts t.to_a.join(", ")

If multiple type definitions are returned, returns them sorted as follows:

1. Complete definitions sort before incomplete ones;
2. IANA-registered definitions sort before LTSW-recorded
3. Generic definitions sort before platform-specific ones;
4. Current definitions sort before obsolete ones;
5. Obsolete definitions with use-instead clauses sort before those
6. Obsolete definitions use-instead clauses are compared.
7. Sort on name.

An additional flag of :platform (finds only MIME::Types for the current platform) is currently supported but deprecated.

# File lib/mime/types.rb, line 133
def [](type_id, flags = {})
  if flags[:platform]
    MIME.deprecated(self, __method__, "using the :platform flag")

  matches = case type_id
            when MIME::Type
            when Regexp

  prune_matches(matches, flags).sort { |a, b| a.priority_compare(b) }
add(*types) click to toggle source

Add one or more MIME::Type objects to the set of known types. If the type is already known, a warning will be displayed.

The last parameter may be the value :silent or true which will suppress duplicate MIME type warnings.

# File lib/mime/types.rb, line 185
def add(*types)
  quiet = ((types.last == :silent) or (types.last == true))

  types.each do |mime_type|
    case mime_type
    when true, false, nil, Symbol
    when MIME::Types
      variants = mime_type.instance_variable_get(:@type_variants)
      add(*variants.values.flatten, quiet)
    when Array
      add(*mime_type, quiet)
      add_type(mime_type, quiet)
add_type(mime_type, quiet = false) click to toggle source

Add a single MIME::Type object to the set of known types. If the type is already known, a warning will be displayed. The quiet parameter may be a truthy value to suppress that warning.

# File lib/mime/types.rb, line 206
def add_type(mime_type, quiet = false)
  if !quiet and @type_variants[mime_type.simplified].include?(mime_type)
    warn("Type %s is already registered as a variant of %s." % [
      mime_type, mime_type.simplified ])

cache_file() click to toggle source

Returns the currently defined cache file, if any.

# File lib/mime/types.rb, line 254
def cache_file
  MIME.deprecated(self, __method__)
count() click to toggle source

Returns the number of known type variants.

# File lib/mime/types.rb, line 93
def count
  @type_variants.values.reduce(0) { |m, o| m + o.size }
each() { |t| ... } click to toggle source

Iterates through the type variants.

# File lib/mime/types.rb, line 98
def each
  @type_variants.values.each { |tv| tv.each { |t| yield t } }
load_from_file(filename) click to toggle source

Load MIME::Types from a v1 file registry.

This method has been deprecated.

# File lib/mime/types.rb, line 222
def load_from_file(filename)
  MIME.deprecated(self, __method__)
of(filename, platform = false)
Alias for: type_for
type_for(filename, platform = false) click to toggle source

Return the list of MIME::Types which belongs to the file based on its filename extension. If there is no extension, the filename will be used as the matching criteria on its own.

This will always return a merged, flatten, priority sorted, unique array.

puts MIME::Types.type_for('citydesk.xml')
  => [application/xml, text/xml]
puts MIME::Types.type_for('citydesk.gif')
  => [image/gif]
puts MIME::Types.type_for(%w(citydesk.xml citydesk.gif))
  => [application/xml, image/gif, text/xml]

If platform is true, then only file types that are specific to the current platform will be returned. This parameter has been deprecated.

# File lib/mime/types.rb, line 165
def type_for(filename, platform = false)
  types = Array(filename) { |fn|
    @extension_index[File.basename(fn.chomp.downcase).gsub(/.*\./o, '')]
  }.flatten.sort { |a, b| a.priority_compare(b) }.uniq

  if platform
    MIME.deprecated(self, __method__,
                    "using the platform parameter")
Also aliased as: of