class MIME::Type

The definition of one MIME content-type.

Usage

require 'mime/types'

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

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

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

puts MIME::Types.any? { |type|
  type.content_type == 'text/plain'
}                               # => true
puts MIME::Types.all?(&:registered?)
                                # => false

Constants

VERSION

The released version of the mime-types library.

Attributes

content_type[R]

Returns the whole MIME content-type string.

The content type is a presentation value from the MIME type registry and should not be used for comparison. The case of the content type is preserved, and extension markers (x-) are kept.

text/plain        => text/plain
x-chemical/x-pdb  => x-chemical/x-pdb
audio/QCELP       => audio/QCELP
docs[RW]

The documentation for this MIME::Type.

encoding[RW]

The encoding (7bit, 8bit, quoted-printable, or base64) required to transport the data of this content type safely across a network, which roughly corresponds to Content-Transfer-Encoding. A value of nil or :default will reset the encoding to the default_encoding for the MIME::Type. Raises ArgumentError if the encoding provided is invalid.

If the encoding is not provided on construction, this will be either 'quoted-printable' (for text/* media types) and 'base64' for eveything else.

extensions[R]

The list of extensions which are known to be used for this MIME::Type. Non-array values will be coerced into an array with to_a. Array values will be flattened, nil values removed, and made unique.

i18n_key[R]

A key suitable for use as a lookup key for translations, such as with the I18n library.

call-seq:

text_plain.i18n_key # => "text.plain"
3gpp_xml.i18n_key   # => "application.vnd-3gpp-bsf-xml"
  # from application/vnd.3gpp.bsf+xml
x_msword.i18n_key   # => "application.word"
  # from application/x-msword
media_type[R]

Returns the media type of the simplified MIME::Type.

text/plain        => text
x-chemical/x-pdb  => chemical
preferred_extension[R]

The preferred extension for this MIME type, if one is set.

raw_media_type[R]

Returns the media type of the unmodified MIME::Type.

text/plain        => text
x-chemical/x-pdb  => x-chemical
raw_sub_type[R]

Returns the media type of the unmodified MIME::Type.

text/plain        => plain
x-chemical/x-pdb  => x-pdb
references[RW]

The encoded references URL list for this MIME::Type. See urls for more information.

This was previously called url.

references has been deprecated and both versions (#references and url) will be removed in mime-types 3.

simplified[R]

A simplified form of the MIME content-type string, suitable for case-insensitive comparison, with any extension markers (<tt>x-</tt) removed and converted to lowercase.

text/plain        => text/plain
x-chemical/x-pdb  => chemical/pdb
audio/QCELP       => audio/qcelp
sub_type[R]

Returns the sub-type of the simplified MIME::Type.

text/plain        => plain
x-chemical/x-pdb  => pdb
url[RW]

The encoded references URL list for this MIME::Type. See urls for more information.

urls has been deprecated and both versions (#references and url) will be removed in mime-types 3.

use_instead[RW]

Returns the media type or types that should be used instead of this media type, if it is obsolete. If there is no replacement media type, or it is not obsolete, nil will be returned.

xrefs[RW]

The cross-references list for this MIME::Type.

Public Class Methods

from_array(*args) { |t| ... } click to toggle source

Creates a MIME::Type from an args array in the form of:

[ type-name, [ extensions ], encoding, system ]

extensions, encoding, and system are optional.

MIME::Type.from_array('application/x-ruby', %w(rb), '8bit')
MIME::Type.from_array([ 'application/x-ruby', [ 'rb' ], '8bit' ])

These are equivalent to:

MIME::Type.new('application/x-ruby') do |t|
  t.extensions  = %w(rb)
  t.encoding    = '8bit'
end

It will yield the type (t) if a block is given.

This method is deprecated and will be removed in mime-types 3.

# File lib/mime/type.rb, line 733
def from_array(*args) # :yields t:
  MIME::Types.deprecated(self, __method__)

  # Dereferences the array one level, if necessary.
  args = args.first if args.first.kind_of? Array

  unless args.size.between?(1, 8)
    fail ArgumentError,
         'Array provided must contain between one and eight elements.'
  end

  MIME::Type.new(args.shift) do |t|
    t.extensions, t.encoding, t.system, t.obsolete, t.docs, t.references,
      t.registered = *args
    yield t if block_given?
  end
end
from_hash(hash) { |t| ... } click to toggle source

Creates a MIME::Type from a hash. Keys are case-insensitive, dashes may be replaced with underscores, and the internal Symbol of the lowercase-underscore version can be used as well. That is, Content-Type can be provided as content-type, Content_Type, #content_type, or :content_type.

Known keys are Content-Type, Content-Transfer-Encoding, Extensions, and System.

MIME::Type.from_hash('Content-Type' => 'text/x-yaml',
                     'Content-Transfer-Encoding' => '8bit',
                     'System' => 'linux',
                     'Extensions' => ['yaml', 'yml'])

This is equivalent to:

MIME::Type.new('text/x-yaml') do |t|
  t.encoding    = '8bit'
  t.system      = 'linux'
  t.extensions  = ['yaml', 'yml']
end

It will yield the constructed type t if a block has been provided.

This method is deprecated and will be removed in mime-types 3.

# File lib/mime/type.rb, line 778
def from_hash(hash) # :yields t:
  MIME::Types.deprecated(self, __method__)
  type = {}
  hash.each_pair do |k, v|
    type[k.to_s.tr('A-Z', 'a-z').gsub(/-/, '_').to_sym] = v
  end

  MIME::Type.new(type[:content_type]) do |t|
    t.extensions  = type[:extensions]
    t.encoding    = type[:content_transfer_encoding]
    t.system      = type[:system]
    t.obsolete    = type[:obsolete]
    t.docs        = type[:docs]
    t.url         = type[:url]
    t.registered  = type[:registered]

    yield t if block_given?
  end
end
from_mime_type(mime_type) click to toggle source

Essentially a copy constructor for mime_type.

MIME::Type.from_mime_type(plaintext)

is equivalent to:

MIME::Type.new(plaintext.content_type.dup) do |t|
  t.extensions  = plaintext.extensions.dup
  t.system      = plaintext.system.dup
  t.encoding    = plaintext.encoding.dup
end

It will yield the type (t) if a block is given.

This method is deprecated and will be removed in mime-types 3.

# File lib/mime/type.rb, line 813
def from_mime_type(mime_type) # :yields the new MIME::Type:
  MIME::Types.deprecated(self, __method__)
  new(mime_type)
end
i18n_key(content_type) click to toggle source

Converts a provided content_type into a translation key suitable for use with the I18n library.

# File lib/mime/type.rb, line 697
def i18n_key(content_type)
  matchdata = case content_type
              when MatchData
                content_type
              else
                MEDIA_TYPE_RE.match(content_type)
              end

  return unless matchdata

  matchdata.captures.map { |e|
    e.downcase!
    e.gsub!(UNREGISTERED_RE, ''.freeze)
    e.gsub!(I18N_RE, '-'.freeze)
    e
  }.join('.'.freeze)
end
new(content_type) { |self| ... } click to toggle source

Builds a MIME::Type object from the content_type, a MIME Content Type value (e.g., 'text/plain' or 'applicaton/x-eruby'). The constructed object is yielded to an optional block for additional configuration, such as associating extensions and encoding information.

  • When provided a Hash or a MIME::Type, the MIME::Type will be constructed with init_with.

  • When provided an Array, the MIME::Type will be constructed only using the first two elements of the array as the content type and extensions.

  • Otherwise, the #content_type will be used as a string.

Yields the newly constructed self object.

# File lib/mime/type.rb, line 96
def initialize(content_type) # :yields self:
  @friendly = {}
  self.system = nil
  self.obsolete = false
  self.registered = nil
  self.use_instead = nil
  self.signature = nil

  case content_type
  when Hash
    init_with(content_type)
  when Array
    self.content_type = content_type[0]
    self.extensions = content_type[1] || []
  when MIME::Type
    init_with(content_type.to_h)
  else
    self.content_type = content_type
  end

  self.extensions ||= []
  self.docs ||= []
  self.encoding ||= :default
  # This value will be deprecated in the future, as it will be an
  # alternative view on #xrefs. Silence an unnecessary warning for now by
  # assigning directly to the instance variable.
  @references ||= []
  self.xrefs ||= {}

  yield self if block_given?
end
simplified(content_type) click to toggle source

The MIME types main- and sub-label can both start with x-, which indicates that it is a non-registered name. Of course, after registration this flag may disappear, adds to the confusing proliferation of MIME types. The simplified content_type string has the x- removed and is translated to lowercase.

# File lib/mime/type.rb, line 678
def simplified(content_type)
  matchdata = case content_type
              when MatchData
                content_type
              else
                MEDIA_TYPE_RE.match(content_type)
              end

  return unless matchdata

  matchdata.captures.map { |e|
    e.downcase!
    e.gsub!(UNREGISTERED_RE, ''.freeze)
    e
  }.join('/'.freeze)
end

Public Instance Methods

<=>(other) click to toggle source

Compares the other MIME::Type against the exact content type or the simplified type (the simplified type will be used if comparing against something that can be treated as a String with to_s). In comparisons, this is done against the lowercase version of the MIME::Type.

# File lib/mime/type.rb, line 141
def <=>(other)
  if other.respond_to?(:content_type)
    @content_type.downcase <=> other.content_type.downcase
  elsif other.respond_to?(:to_s)
    @simplified <=> MIME::Type.simplified(other.to_s)
  end
end
add_extensions(*extensions) click to toggle source

Merge the extensions provided into this MIME::Type. The extensions added will be merged uniquely.

# File lib/mime/type.rb, line 250
def add_extensions(*extensions)
  self.extensions = self.extensions + extensions
end
ascii?() click to toggle source

MIME types can be specified to be sent across a network in particular formats. This method returns false when the MIME::Type encoding is set to base64.

# File lib/mime/type.rb, line 538
def ascii?
  !binary?
end
binary?() click to toggle source

MIME types can be specified to be sent across a network in particular formats. This method returns true when the MIME::Type encoding is set to base64.

# File lib/mime/type.rb, line 531
def binary?
  BINARY_ENCODINGS.include?(@encoding)
end
complete?() click to toggle source

Returns true if the MIME::Type specifies an extension list, indicating that it is a complete MIME::Type.

# File lib/mime/type.rb, line 571
def complete?
  !@extensions.empty?
end
default_encoding() click to toggle source

Returns the default encoding for the MIME::Type based on the media type.

# File lib/mime/type.rb, line 309
def default_encoding
  (@media_type == 'text') ? 'quoted-printable' : 'base64'
end
encode_with(coder) click to toggle source

Populates the coder with attributes about this record for serialization. The structure of coder should match the structure used with init_with.

This method should be considered a private implementation detail.

# File lib/mime/type.rb, line 632
def encode_with(coder)
  coder['content-type']   = @content_type
  coder['docs']           = @docs unless @docs.nil? or @docs.empty?
  coder['friendly']       = @friendly unless @friendly.empty?
  coder['encoding']       = @encoding
  coder['extensions']     = @extensions unless @extensions.empty?
  if obsolete?
    coder['obsolete']     = obsolete?
    coder['use-instead']  = use_instead if use_instead
  end
  coder['references']     = references(true) unless references(true).empty?
  coder['xrefs']          = xrefs unless xrefs.empty?
  coder['registered']     = registered?
  coder['signature']      = signature? if signature?
  coder['system']         = @system if @system
  coder
end
eql?(other) click to toggle source

Returns true if the other object is a MIME::Type and the content types match.

# File lib/mime/type.rb, line 195
def eql?(other)
  other.kind_of?(MIME::Type) and self == other
end
friendly # → "Text File" click to toggle source
friendly('en') # → "Text File"

A friendly short description for this MIME::Type.

# File lib/mime/type.rb, line 346
def friendly(lang = 'en'.freeze)
  @friendly ||= {}

  case lang
  when String
    @friendly[lang]
  when Array
    @friendly.merge!(Hash[*lang])
  when Hash
    @friendly.merge!(lang)
  else
    fail ArgumentError
  end
end
init_with(coder) click to toggle source

Initialize an empty object from coder, which must contain the attributes necessary for initializing an empty object.

This method should be considered a private implementation detail.

# File lib/mime/type.rb, line 654
def init_with(coder)
  self.content_type = coder['content-type']
  self.docs         = coder['docs'] || []
  friendly(coder['friendly'] || {})
  self.encoding     = coder['encoding']
  self.extensions   = coder['extensions'] || []
  self.obsolete     = coder['obsolete']
  # This value will be deprecated in the future, as it will be an
  # alternative view on #xrefs. Silence an unnecessary warning for now by
  # assigning directly to the instance variable.
  @references       = Array(coder['references']).flatten.compact.uniq
  self.registered   = coder['registered']
  self.signature    = coder['signature']
  self.system       = coder['system']
  self.xrefs        = coder['xrefs'] || {}
  self.use_instead  = coder['use-instead']
end
like?(other) click to toggle source

Returns true if the other simplified type matches the current type.

# File lib/mime/type.rb, line 129
def like?(other)
  if other.respond_to?(:simplified)
    @simplified == other.simplified
  else
    @simplified == MIME::Type.simplified(other)
  end
end
obsolete?() click to toggle source

Returns true if the media type is obsolete.

# File lib/mime/type.rb, line 330
def obsolete?
  !!@obsolete
end
platform?(__internal__ = false) click to toggle source

Returns true if the MIME::Type is specific to the current operating system as represented by RUBY_PLATFORM.

This method is deprecated and will be removed in mime-types 3.

# File lib/mime/type.rb, line 564
def platform?(__internal__ = false)
  MIME::Types.deprecated(self, __method__) unless __internal__
  system?(__internal__) and (RUBY_PLATFORM =~ @system)
end
priority_compare(other) click to toggle source

Compares the other MIME::Type based on how reliable it is before doing a normal <=> comparison. Used by MIME::Types#[] to sort types. The comparisons involved are:

  1. self.simplified <=> other.simplified (ensures that we don't try to compare different types)

  2. IANA-registered definitions < other definitions.

  3. Generic definitions < platform definitions.

  4. Complete definitions < incomplete definitions.

  5. Current definitions < obsolete definitions.

  6. Obselete with use-instead references < obsolete without.

  7. Obsolete use-instead definitions are compared.

While this method is public, its use is strongly discouraged by consumers of mime-types. In mime-types 3, this method is likely to see substantial revision and simplification to ensure current registered content types sort before unregistered or obsolete content types.

# File lib/mime/type.rb, line 166
def priority_compare(other)
  pc = simplified <=> other.simplified
  if pc.zero?
    pc = if (reg = registered?) != other.registered?
           reg ? -1 : 1 # registered < unregistered
         elsif (plat = platform?(true)) != other.platform?(true)
           plat ? 1 : -1 # generic < platform
         elsif (comp = complete?) != other.complete?
           comp ? -1 : 1 # complete < incomplete
         elsif (obs = obsolete?) != other.obsolete?
           obs ? 1 : -1 # current < obsolete
         elsif obs and ((ui = use_instead) != (oui = other.use_instead))
           if ui.nil?
             1
           elsif oui.nil?
             -1
           else
             ui <=> oui
           end
         else
           0
         end
  end

  pc
end
registered?() click to toggle source

Prior to BCP 178 (RFC 6648), it could be assumed that MIME content types that start with x- were unregistered MIME. Per this BCP, this assumption is no longer being made by default in this library.

There are three possible registration states for a MIME::Type:

  • Explicitly registered, like application/x-www-url-encoded.

  • Explicitly not registered, like image/webp.

  • Unspecified, in which case the media-type and the content-type will be scanned to see if they start with x-, indicating that they are assumed unregistered.

In mime-types 3, only a MIME content type that is explicitly registered will be used; there will be assumption that x- types are unregistered.

# File lib/mime/type.rb, line 515
def registered?
  if @registered.nil?
    (@raw_media_type !~ UNREGISTERED_RE) and
      (@raw_sub_type !~ UNREGISTERED_RE)
  else
    !!@registered
  end
end
signature?() click to toggle source

Returns true when the simplified MIME::Type is one of the known digital signature types.

# File lib/mime/type.rb, line 544
def signature?
  !!@signature
end
system() click to toggle source

If the MIME::Type is a system-specific MIME::Type, returns the regular expression for the operating system indicated.

This information about MIME content types is deprecated and will be removed in mime-types 3.

# File lib/mime/type.rb, line 295
def system
  MIME::Types.deprecated(self, __method__)
  @system
end
system?(__internal__ = false) click to toggle source

Returns true if the MIME::Type is specific to an operating system.

This method is deprecated and will be removed in mime-types 3.

# File lib/mime/type.rb, line 555
def system?(__internal__ = false)
  MIME::Types.deprecated(self, __method__) unless __internal__
  !@system.nil?
end
to_a() click to toggle source

Returns the MIME::Type as an array suitable for use with ::from_array.

This method is deprecated and will be removed in mime-types 3.

# File lib/mime/type.rb, line 592
def to_a
  MIME::Types.deprecated(self, __method__)
  [ @content_type, @extensions, @encoding, @system, obsolete?, @docs,
    @references, registered? ]
end
to_h() click to toggle source

Converts the MIME::Type to a hash suitable for use in JSON. The output of this method can also be used to initialize a MIME::Type.

# File lib/mime/type.rb, line 623
def to_h
  encode_with({})
end
to_hash() click to toggle source

Returns the MIME::Type as an array suitable for use with ::from_hash.

This method is deprecated and will be removed in mime-types 3.

# File lib/mime/type.rb, line 602
def to_hash
  MIME::Types.deprecated(self, __method__)
  { 'Content-Type'              => @content_type,
    'Content-Transfer-Encoding' => @encoding,
    'Extensions'                => @extensions,
    'System'                    => @system,
    'Obsolete'                  => obsolete?,
    'Docs'                      => @docs,
    'URL'                       => @references,
    'Registered'                => registered?,
  }
end
to_json(*args) click to toggle source

Converts the MIME::Type to a JSON string.

# File lib/mime/type.rb, line 616
def to_json(*args)
  require 'json'
  to_h.to_json(*args)
end
to_s() click to toggle source

Returns the MIME::Type as a string.

# File lib/mime/type.rb, line 576
def to_s
  content_type
end
to_str() click to toggle source

Returns the MIME::Type as a string for implicit conversions. This allows MIME::Type objects to appear on either side of a comparison.

'text/plain' == MIME::Type.new('text/plain')
# File lib/mime/type.rb, line 584
def to_str
  content_type
end
urls() click to toggle source

The decoded URL list for this MIME::Type.

The special URL value IANA will be translated into:

http://www.iana.org/assignments/media-types/<mediatype>/<subtype>

The special URL value RFC### will be translated into:

http://www.rfc-editor.org/rfc/rfc###.txt

The special URL value DRAFT:name will be translated into:

https://datatracker.ietf.org/public/idindex.cgi?
    command=id_detail&filename=<name>

The special URL value [token] will be translated into:

http://www.iana.org/assignments/contact-people.htm#<token>

These values will be accessible through urls, which always returns an array.

This method is deprecated and will be removed in mime-types 3.

# File lib/mime/type.rb, line 450
def urls
  MIME::Types.deprecated(self, __method__)
  references(true).map do |el|
    case el
    when %r{^IANA$}
      IANA_URL % [ @media_type, @sub_type ]
    when %r{^RFC(\d+)$}
      RFC_URL % $1
    when %r{^DRAFT:(.+)$}
      DRAFT_URL % $1
    when %r{^\{([^=]+)=([^\}]+)\}}
      [$1, $2]
    when %r{^\[([^=]+)=([^\]]+)\]}
      [$1, CONTACT_URL % $2]
    when %r{^\[([^\]]+)\]}
      CONTACT_URL % $1
    else
      el
    end
  end
end
xref_urls() click to toggle source

The decoded cross-reference URL list for this MIME::Type.

# File lib/mime/type.rb, line 473
def xref_urls
  xrefs.flat_map { |(type, values)|
    case type
    when 'rfc'.freeze
      values.map { |data| 'http://www.iana.org/go/%s'.freeze % data }
    when 'draft'.freeze
      values.map { |data|
        'http://www.iana.org/go/%s'.freeze % data.sub(/\ARFC/, 'draft')
      }
    when 'rfc-errata'.freeze
      values.map { |data|
        'http://www.rfc-editor.org/errata_search.php?eid=%s'.freeze % data
      }
    when 'person'.freeze
      values.map { |data|
        'http://www.iana.org/assignments/media-types/media-types.xhtml#%s'.freeze % data # rubocop:disable Metrics/LineLength
      }
    when 'template'.freeze
      values.map { |data|
        'http://www.iana.org/assignments/media-types/%s'.freeze % data
      }
    else # 'uri', 'text', etc.
      values
    end
  }
end

Private Instance Methods

content_type=(type_string) click to toggle source
# File lib/mime/type.rb, line 821
def content_type=(type_string)
  match = MEDIA_TYPE_RE.match(type_string)
  fail InvalidContentType, type_string if match.nil?

  @content_type                  = type_string
  @raw_media_type, @raw_sub_type = match.captures
  @simplified                    = MIME::Type.simplified(match)
  @i18n_key                      = MIME::Type.i18n_key(match)
  @media_type, @sub_type         = MEDIA_TYPE_RE.match(@simplified).captures
end