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.

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  => x-chemical
audio/QCELP       => audio
obsolete[RW]

Returns true if the media type is obsolete.

obsolete?[RW]

Returns true if the media type is obsolete.

preferred_extension[RW]

The preferred extension for this MIME type. If one is not set and there are exceptions defined, the first extension will be used.

When setting preferred_extensions, if extensions does not contain this extension, this will be added to xtensions.

raw_media_type[R]

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

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

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

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

Indicates whether the MIME type has been registered with IANA.

registered?[RW]

Indicates whether the MIME type has been registered with IANA.

signature[RW]

Indicateswhether the MIME type is declared as a signature type.

signature?[RW]

Indicateswhether the MIME type is declared as a signature type.

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  => x-chemical/x-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
audio/QCELP       => QCELP
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

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 505
def i18n_key(content_type)
  simplify_matchdata(match(content_type), joiner: '.') { |e|
    e.gsub!(I18N_RE, '-'.freeze)
  }
end
match(content_type) click to toggle source

Return a MatchData object of the content_type against pattern of media types.

# File lib/mime/type.rb, line 513
def match(content_type)
  case content_type
  when MatchData
    content_type
  else
    MEDIA_TYPE_RE.match(content_type)
  end
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 using the first element as the content type and the remaining flattened elements as extensions.

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

Yields the newly constructed self object.

# File lib/mime/type.rb, line 89
def initialize(content_type) # :yields self:
  @friendly = {}
  @obsolete = @registered = false
  @preferred_extension = @docs = @use_instead = nil
  self.extensions = []

  case content_type
  when Hash
    init_with(content_type)
  when Array
    self.content_type = content_type.shift
    self.extensions = content_type.flatten
  when MIME::Type
    init_with(content_type.to_h)
  else
    self.content_type = content_type
  end

  self.encoding ||= :default
  self.xrefs ||= {}

  yield self if block_given?
end
simplified(content_type, remove_x_prefix: false) click to toggle source

MIME media types are case-insensitive, but are typically presented in a case-preserving format in the type registry. This method converts content_type to lowercase.

In previous versions of mime-types, this would also remove any extension prefix (x-). This is no longer default behaviour, but may be provided by providing a truth value to remove_x_prefix.

# File lib/mime/type.rb, line 499
def simplified(content_type, remove_x_prefix: false)
  simplify_matchdata(match(content_type), remove_x_prefix)
end

Private Class Methods

simplify_matchdata(matchdata, remove_x = false, joiner: '/'.freeze) { |e| ... } click to toggle source
# File lib/mime/type.rb, line 524
def simplify_matchdata(matchdata, remove_x = false, joiner: '/'.freeze)
  return nil unless matchdata

  matchdata.captures.map { |e|
    e.downcase!
    e.sub!(%r{^x-}, ''.freeze) if remove_x
    yield e if block_given?
    e
  }.join(joiner)
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 128
def <=>(other)
  if other.nil?
    -1
  elsif other.respond_to?(:simplified)
    simplified <=> other.simplified
  else
    filtered = 'silent' if other == :silent
    filtered ||= 'true' if other == true
    filtered ||= other.to_s

    simplified <=> MIME::Type.simplified(filtered)
  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 += 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 396
def ascii?
  ASCII_ENCODINGS.include?(encoding)
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 389
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 406
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 303
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 440
def encode_with(coder)
  coder['content-type']        = @content_type
  coder['docs']                = @docs unless @docs.nil? or @docs.empty?
  unless @friendly.nil? or @friendly.empty?
    coder['friendly']            = @friendly
  end
  coder['encoding']            = @encoding
  coder['extensions']          = @extensions.to_a unless @extensions.empty?
  coder['preferred-extension'] = @preferred_extension if @preferred_extension
  if obsolete?
    coder['obsolete']          = obsolete?
    coder['use-instead']       = use_instead if use_instead
  end
  unless xrefs.empty?
    {}.tap do |hash|
      xrefs.each do |k, v|
        hash[k] = v.to_a.sort
      end
      coder['xrefs'] = hash
    end
  end
  coder['registered']          = registered?
  coder['signature']           = signature? if signature?
  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 185
def eql?(other)
  other.kind_of?(MIME::Type) and self == other
end
extensions() click to toggle source

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.

:attr_accessor: extensions

# File lib/mime/type.rb, line 238
def extensions
  @extensions.to_a
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 334
def friendly(lang = 'en'.freeze)
  @friendly ||= {}

  case lang
  when String, Symbol
    @friendly[lang.to_s]
  when Array
    @friendly.update(Hash[*lang])
  when Hash
    @friendly.update(lang)
  else
    fail ArgumentError,
      "Expected a language or translation set, not #{lang.inspect}"
  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 470
def init_with(coder)
  self.content_type        = coder['content-type']
  self.docs                = coder['docs'] || ''
  self.encoding            = coder['encoding']
  self.extensions          = coder['extensions'] || []
  self.preferred_extension = coder['preferred-extension']
  self.obsolete            = coder['obsolete'] || false
  self.registered          = coder['registered'] || false
  self.signature           = coder['signature']
  self.xrefs               = coder['xrefs'] || {}
  self.use_instead         = coder['use-instead']

  friendly(coder['friendly'] || {})
end
like?(other) click to toggle source

Indicates that a MIME type is like another type. This differs from == because x- prefixes are removed for this comparison.

# File lib/mime/type.rb, line 115
def like?(other)
  other = if other.respond_to?(:simplified)
            MIME::Type.simplified(other.simplified, remove_x_prefix: true)
          else
            MIME::Type.simplified(other.to_s, remove_x_prefix: true)
          end
  MIME::Type.simplified(simplified, remove_x_prefix: true) == other
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. Complete definitions < incomplete definitions.

  4. Current definitions < obsolete definitions.

  5. Obselete with use-instead names < obsolete without.

  6. 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 158
def priority_compare(other)
  pc = simplified <=> other.simplified
  if pc.zero? || !(extensions & other.extensions).empty?
    pc = if (reg = registered?) != other.registered?
           reg ? -1 : 1 # registered < unregistered
         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
to_h() click to toggle source

Converts the MIME::Type to a hash. The output of this method can also be used to initialize a MIME::Type.

# File lib/mime/type.rb, line 431
def to_h
  encode_with({})
end
to_json(*args) click to toggle source

Converts the MIME::Type to a JSON string.

# File lib/mime/type.rb, line 424
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 411
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 419
def to_str
  content_type
end
xref_urls() click to toggle source

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

# File lib/mime/type.rb, line 375
def xref_urls
  xrefs.flat_map { |type, values|
    name = :"xref_url_for_#{type.tr('-', '_')}"
    respond_to?(name, true) and xref_map(values, name) or values.to_a
  }
end

Private Instance Methods

content_type=(type_string) click to toggle source
# File lib/mime/type.rb, line 538
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
xref_map(values, helper) click to toggle source
# File lib/mime/type.rb, line 549
def xref_map(values, helper)
  values.map { |value| send(helper, value) }
end
xref_url_for_draft(value) click to toggle source
# File lib/mime/type.rb, line 557
def xref_url_for_draft(value)
  'http://www.iana.org/go/%s'.freeze % value.sub(/\ARFC/, 'draft')
end
xref_url_for_person(value) click to toggle source
# File lib/mime/type.rb, line 565
def xref_url_for_person(value)
  'http://www.iana.org/assignments/media-types/media-types.xhtml#%s'.freeze %
    value
end
xref_url_for_rfc(value) click to toggle source
# File lib/mime/type.rb, line 553
def xref_url_for_rfc(value)
  'http://www.iana.org/go/%s'.freeze % value
end
xref_url_for_rfc_errata(value) click to toggle source
# File lib/mime/type.rb, line 561
def xref_url_for_rfc_errata(value)
  'http://www.rfc-editor.org/errata_search.php?eid=%s'.freeze % value
end
xref_url_for_template(value) click to toggle source
# File lib/mime/type.rb, line 570
def xref_url_for_template(value)
  'http://www.iana.org/assignments/media-types/%s'.freeze % value
end