Class: MIME::Type

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/mime/type.rb

Overview

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

Direct Known Subclasses

Columnar

Defined Under Namespace

Classes: Columnar, InvalidContentType, InvalidEncoding

Constant Summary collapse

VERSION =

The released version of the mime-types library.

'2.99.3'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content_type) {|_self| ... } ⇒ Type

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.

Yields:

  • (_self)

Yield Parameters:

  • _self (MIME::Type)

    the object that the method was called on



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/mime/type.rb', line 97

def initialize(content_type) # :yields self:
  @friendly = {}
  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
  self.xrefs ||= {}

  yield self if block_given?
end

Instance Attribute Details

#content_typeObject

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


201
202
203
# File 'lib/mime/type.rb', line 201

def content_type
  @content_type
end

#docsObject

The documentation for this MIME::Type.



329
330
331
# File 'lib/mime/type.rb', line 329

def docs
  @docs
end

#encodingObject

Returns the value of attribute encoding.



272
273
274
# File 'lib/mime/type.rb', line 272

def encoding
  @encoding
end

#extensionsObject

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.



234
235
236
# File 'lib/mime/type.rb', line 234

def extensions
  @extensions
end

#i18n_keyObject (readonly)

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


360
361
362
# File 'lib/mime/type.rb', line 360

def i18n_key
  @i18n_key
end

#media_typeObject (readonly)

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

text/plain        => text
x-chemical/x-pdb  => chemical


214
215
216
# File 'lib/mime/type.rb', line 214

def media_type
  @media_type
end

#raw_media_typeObject (readonly)

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

text/plain        => text
x-chemical/x-pdb  => x-chemical


219
220
221
# File 'lib/mime/type.rb', line 219

def raw_media_type
  @raw_media_type
end

#raw_sub_typeObject (readonly)

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

text/plain        => plain
x-chemical/x-pdb  => x-pdb


229
230
231
# File 'lib/mime/type.rb', line 229

def raw_sub_type
  @raw_sub_type
end

#simplifiedObject (readonly)

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


209
210
211
# File 'lib/mime/type.rb', line 209

def simplified
  @simplified
end

#sub_typeObject (readonly)

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

text/plain        => plain
x-chemical/x-pdb  => pdb


224
225
226
# File 'lib/mime/type.rb', line 224

def sub_type
  @sub_type
end

#use_insteadObject



311
312
313
314
# File 'lib/mime/type.rb', line 311

def use_instead
  return nil unless obsolete?
  @use_instead
end

#xrefsObject

Returns the value of attribute xrefs.



412
413
414
# File 'lib/mime/type.rb', line 412

def xrefs
  @xrefs
end

Class Method Details

.from_array(*args) ⇒ Object

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

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

extensions, and encoding are optional; system is ignored.

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.



701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
# File 'lib/mime/type.rb', line 701

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, _system, t.obsolete, t.docs, _references,
      t.registered = *args
    yield t if block_given?
  end
end

.from_hash(hash) ⇒ Object

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. System is ignored.

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.



746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
# File 'lib/mime/type.rb', line 746

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.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) ⇒ Object

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.



780
781
782
783
# File 'lib/mime/type.rb', line 780

def from_mime_type(mime_type) # :yields the new MIME::Type:
  MIME::Types.deprecated(self, __method__)
  new(mime_type)
end

.i18n_key(content_type) ⇒ Object

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



665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
# File 'lib/mime/type.rb', line 665

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

.simplified(content_type) ⇒ Object

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.



646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
# File 'lib/mime/type.rb', line 646

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

Instance Method Details

#<=>(other) ⇒ Object

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.



137
138
139
140
141
142
143
# File 'lib/mime/type.rb', line 137

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) ⇒ Object

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



243
244
245
# File 'lib/mime/type.rb', line 243

def add_extensions(*extensions)
  self.extensions = self.extensions + extensions
end

#ascii?Boolean

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.

Returns:

  • (Boolean)


511
512
513
# File 'lib/mime/type.rb', line 511

def ascii?
  !binary?
end

#binary?Boolean

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.

Returns:

  • (Boolean)


504
505
506
# File 'lib/mime/type.rb', line 504

def binary?
  BINARY_ENCODINGS.include?(@encoding)
end

#complete?Boolean

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

Returns:

  • (Boolean)


546
547
548
# File 'lib/mime/type.rb', line 546

def complete?
  !@extensions.empty?
end

#default_encodingObject

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



299
300
301
# File 'lib/mime/type.rb', line 299

def default_encoding
  (@media_type == 'text') ? 'quoted-printable' : 'base64'
end

#encode_with(coder) ⇒ Object

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.



607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
# File 'lib/mime/type.rb', line 607

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['xrefs']          = xrefs unless xrefs.empty?
  coder['registered']     = registered?
  coder['signature']      = signature? if signature?
  coder
end

#eql?(other) ⇒ Boolean

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

Returns:

  • (Boolean)


188
189
190
# File 'lib/mime/type.rb', line 188

def eql?(other)
  other.kind_of?(MIME::Type) and self == other
end

#friendly(lang = 'en'.freeze) ⇒ Object

A friendly short description for this MIME::Type.

call-seq:

text_plain.friendly         # => "Text File"
text_plain.friendly('en')   # => "Text File"


336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/mime/type.rb', line 336

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) ⇒ Object

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.



627
628
629
630
631
632
633
634
635
636
637
638
# File 'lib/mime/type.rb', line 627

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']
  self.registered   = coder['registered']
  self.signature    = coder['signature']
  self.xrefs        = coder['xrefs'] || {}
  self.use_instead  = coder['use-instead']
end

#like?(other) ⇒ Boolean

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

Returns:

  • (Boolean)


125
126
127
128
129
130
131
# File 'lib/mime/type.rb', line 125

def like?(other)
  if other.respond_to?(:simplified)
    @simplified == other.simplified
  else
    @simplified == MIME::Type.simplified(other)
  end
end

#obsolete=(v) ⇒ Object

:nodoc:



324
325
326
# File 'lib/mime/type.rb', line 324

def obsolete=(v) # :nodoc:
  @obsolete = !!v
end

#obsolete?Boolean

Returns true if the media type is obsolete.

Returns:

  • (Boolean)


320
321
322
# File 'lib/mime/type.rb', line 320

def obsolete?
  !!@obsolete
end

#platform?Boolean

Returns false. Prior to mime-types 2.99, would return 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.

Returns:

  • (Boolean)


539
540
541
542
# File 'lib/mime/type.rb', line 539

def platform?(*)
  MIME::Types.deprecated(self, __method__)
  false
end

#preferred_extensionObject



253
254
255
# File 'lib/mime/type.rb', line 253

def preferred_extension
  extensions.first
end

#priority_compare(other) ⇒ Object

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.



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/mime/type.rb', line 161

def priority_compare(other)
  pc = simplified <=> other.simplified
  if pc.zero?
    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

#referencesObject



375
376
377
378
# File 'lib/mime/type.rb', line 375

def references(*)
  MIME::Types.deprecated(self, __method__)
  []
end

#references=(_r) ⇒ Object

:nodoc:



381
382
383
# File 'lib/mime/type.rb', line 381

def references=(_r) # :nodoc:
  MIME::Types.deprecated(self, __method__)
end

#registered=(v) ⇒ Object

:nodoc:



497
498
499
# File 'lib/mime/type.rb', line 497

def registered=(v) # :nodoc:
  @registered = v.nil? ? v : !!v
end

#registered?Boolean

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.

Returns:

  • (Boolean)


488
489
490
491
492
493
494
495
# File 'lib/mime/type.rb', line 488

def registered?
  if @registered.nil?
    (@raw_media_type !~ UNREGISTERED_RE) and
      (@raw_sub_type !~ UNREGISTERED_RE)
  else
    !!@registered
  end
end

#signature=(v) ⇒ Object

:nodoc:



521
522
523
# File 'lib/mime/type.rb', line 521

def signature=(v) # :nodoc:
  @signature = !!v
end

#signature?Boolean

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

Returns:

  • (Boolean)


517
518
519
# File 'lib/mime/type.rb', line 517

def signature?
  !!@signature
end

#systemObject

Returns nil and assignments are ignored. Prior to mime-types 2.99, this would return the regular expression for the operating system indicated if the MIME::Type is a system-specific MIME::Type,

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



289
290
291
292
# File 'lib/mime/type.rb', line 289

def system
  MIME::Types.deprecated(self, __method__)
  nil
end

#system=(_os) ⇒ Object

:nodoc:



294
295
296
# File 'lib/mime/type.rb', line 294

def system=(_os) # :nodoc:
  MIME::Types.deprecated(self, __method__)
end

#system?Boolean

Returns false. Prior to mime-types 2.99, would return true if the MIME::Type is specific to an operating system.

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

Returns:

  • (Boolean)


529
530
531
532
# File 'lib/mime/type.rb', line 529

def system?(*)
  MIME::Types.deprecated(self, __method__)
  false
end

#to_aObject

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

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



567
568
569
570
571
# File 'lib/mime/type.rb', line 567

def to_a
  MIME::Types.deprecated(self, __method__)
  [ @content_type, @extensions, @encoding, nil, obsolete?, @docs, [],
    registered? ]
end

#to_hObject

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.



598
599
600
# File 'lib/mime/type.rb', line 598

def to_h
  encode_with({})
end

#to_hashObject

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

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



577
578
579
580
581
582
583
584
585
586
587
588
# File 'lib/mime/type.rb', line 577

def to_hash
  MIME::Types.deprecated(self, __method__)
  { 'Content-Type'              => @content_type,
    'Content-Transfer-Encoding' => @encoding,
    'Extensions'                => @extensions,
    'System'                    => nil,
    'Obsolete'                  => obsolete?,
    'Docs'                      => @docs,
    'URL'                       => [],
    'Registered'                => registered?,
  }
end

#to_json(*args) ⇒ Object

Converts the MIME::Type to a JSON string.



591
592
593
594
# File 'lib/mime/type.rb', line 591

def to_json(*args)
  require 'json'
  to_h.to_json(*args)
end

#to_sObject

Returns the MIME::Type as a string.



551
552
553
# File 'lib/mime/type.rb', line 551

def to_s
  content_type
end

#to_strObject

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')


559
560
561
# File 'lib/mime/type.rb', line 559

def to_str
  content_type
end

#urlObject



396
397
398
399
# File 'lib/mime/type.rb', line 396

def url
  MIME::Types.deprecated(self, __method__)
  []
end

#url=(_r) ⇒ Object

:nodoc:



402
403
404
# File 'lib/mime/type.rb', line 402

def url=(_r) # :nodoc:
  MIME::Types.deprecated(self, __method__)
end

#urlsObject

Returns an empty array. Prior to mime-types 2.99, this returned the decoded URL list for this MIME::Type.

The special URL value IANA was translated into:

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

The special URL value RFC### was translated into:

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

The special URL value DRAFT:name was translated into:

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

The special URL value [token] was translated into:

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

These values were accessible through #urls, which always returns an array.

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



440
441
442
443
# File 'lib/mime/type.rb', line 440

def urls
  MIME::Types.deprecated(self, __method__)
  []
end

#xref_urlsObject

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



446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/mime/type.rb', line 446

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