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

Defined Under Namespace

Classes: InvalidContentType, InvalidEncoding

Constant Summary collapse

VERSION =

The released version of the mime-types library.

'2.0'
MEDIA_TYPE_RE =

:stopdoc:

%r{([-\w.+]+)/([-\w.+]*)}o
UNREGISTERED_RE =
%r{[Xx]-}o
PLATFORM_RE =
%r{#{RUBY_PLATFORM}}o
DEFAULT_ENCODINGS =
[ nil, :default ]
BINARY_ENCODINGS =
%w(base64 8bit)
TEXT_ENCODINGS =
%w(7bit quoted-printable)
VALID_ENCODINGS =
DEFAULT_ENCODINGS + BINARY_ENCODINGS + TEXT_ENCODINGS
IANA_URL =
"http://www.iana.org/assignments/media-types/%s/%s"
RFC_URL =
"http://rfc-editor.org/rfc/rfc%s.txt"
DRAFT_URL =
"http://datatracker.ietf.org/public/idindex.cgi?command=id_details&filename=%s"
LTSW_URL =
"http://www.ltsw.se/knbase/internet/%s.htp"
CONTACT_URL =
"http://www.iana.org/assignments/contact-people.htm#%s"

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 provided 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:

  • (_self)

Yield Parameters:

  • _self (MIME::Type)

    the object that the method was called on



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/mime/type.rb', line 92

def initialize(content_type) # :yields self:
  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         ||= nil
  self.encoding     ||= :default
  self.references   ||= []

  yield self if block_given?
end

Instance Attribute Details

#content_typeObject

Returns the whole MIME content-type string.

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


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

def content_type
  @content_type
end

#docsObject

The documentation for this MIME::Type.



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

def docs
  @docs
end

#encodingObject

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.



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

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.



222
223
224
# File 'lib/mime/type.rb', line 222

def extensions
  @extensions
end

#media_typeObject (readonly)

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

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


194
195
196
# File 'lib/mime/type.rb', line 194

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


199
200
201
# File 'lib/mime/type.rb', line 199

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


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

def raw_sub_type
  @raw_sub_type
end

#referencesObject

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

This was previously called #url.



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

def references
  @references
end

#simplifiedObject (readonly)

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 can disappear, adds to the confusing proliferation of MIME types. The simplified string has the x- removed and are translated to lowercase.

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


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

def simplified
  @simplified
end

#sub_typeObject (readonly)

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

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


204
205
206
# File 'lib/mime/type.rb', line 204

def sub_type
  @sub_type
end

#use_insteadObject

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.



279
280
281
282
# File 'lib/mime/type.rb', line 279

def use_instead
  return nil unless obsolete?
  @use_instead
end

Class Method Details

.from_array(*args) ⇒ Object

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

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

extensions, encoding, and system are optional.

MIME::Type.from_array("application/x-ruby", ['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

This method is deprecated.



543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
# File 'lib/mime/type.rb', line 543

def from_array(*args) # :yields MIME::Type.new:
  MIME.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)
    raise 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) ⇒ 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.

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

This method has been deprecated.



584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
# File 'lib/mime/type.rb', line 584

def from_hash(hash) # :yields MIME::Type.new:
  MIME.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) ⇒ Object

Essentially a copy constructor.

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

This method has been deprecated.



617
618
619
620
# File 'lib/mime/type.rb', line 617

def from_mime_type(mime_type) # :yields the new MIME::Type:
  MIME.deprecated(self, __method__)
  new(mime_type)
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 can disappear, adds to the confusing proliferation of MIME types. The simplified string has the x- removed and are translated to lowercase.



515
516
517
518
519
520
521
522
523
524
525
# File 'lib/mime/type.rb', line 515

def simplified(content_type)
  matchdata = MEDIA_TYPE_RE.match(content_type)

  if matchdata.nil?
    nil
  else
    matchdata.captures.map { |e|
      e.downcase.gsub(UNREGISTERED_RE, '')
    }.join('/')
  end
end

Instance Method Details

#<=>(other) ⇒ Object

Compares the 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.



132
133
134
135
136
137
138
# File 'lib/mime/type.rb', line 132

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(*ext) ⇒ Object

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



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

def add_extensions(*ext)
  @extensions = (@extensions + ext).flatten.compact.sort.uniq
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)


389
390
391
# File 'lib/mime/type.rb', line 389

def ascii?
  not 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)


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

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)


421
422
423
# File 'lib/mime/type.rb', line 421

def complete?
  not @extensions.empty?
end

#default_encodingObject

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



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

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

#encode_with(coder) ⇒ Object

:stopdoc:



477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
# File 'lib/mime/type.rb', line 477

def encode_with(coder)
  coder['content-type']   = @content_type
  coder['docs']           = @docs unless @docs.nil? or @docs.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 unless references.empty?
  coder['registered']     = registered?
  if signature?
    coder['signature']      = signature?
  end
  coder['system']         = @system if @system
  coder
end

#eql?(other) ⇒ Boolean

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

Returns:

  • (Boolean)


181
182
183
# File 'lib/mime/type.rb', line 181

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

#init_with(coder) ⇒ Object



495
496
497
498
499
500
501
502
503
504
505
506
# File 'lib/mime/type.rb', line 495

def init_with(coder)
  self.content_type = coder['content-type']
  self.docs         = coder['docs'] || []
  self.encoding     = coder['encoding']
  self.extensions   = coder['extensions'] || []
  self.obsolete     = coder['obsolete']
  self.references   = coder['references'] || []
  self.registered   = coder['registered']
  self.signature    = coder['signature']
  self.system       = coder['system']
  self.use_instead  = coder['use-instead']
end

#like?(other) ⇒ Boolean

Returns true if the simplified type matches the current

Returns:

  • (Boolean)


120
121
122
123
124
125
126
# File 'lib/mime/type.rb', line 120

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

#obsolete=(v) ⇒ Object

:nodoc:



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

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

#obsolete?Boolean

Returns true if the media type is obsolete.

Returns:

  • (Boolean)


286
287
288
# File 'lib/mime/type.rb', line 286

def obsolete?
  !!@obsolete
end

#platform?Boolean

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

This method is deprecated.

Returns:

  • (Boolean)


414
415
416
417
# File 'lib/mime/type.rb', line 414

def platform?
  MIME.deprecated(self, __method__)
  system? and (RUBY_PLATFORM =~ @system)
end

#priority_compare(other) ⇒ Object

Compares the 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.



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/mime/type.rb', line 152

def priority_compare(other)
  pc = simplified <=> other.simplified
  if pc.zero?
    pc = if (registered? != other.registered?)
           registered? ? -1 : 1 # registered < unregistered
         elsif (platform? != other.platform?)
           platform? ? 1 : -1 # generic < platform
         elsif (complete? != other.complete?)
           complete? ? -1 : 1 # complete < incomplete
         elsif (obsolete? != other.obsolete?)
           obsolete? ? 1 : -1 # current < obsolete
         elsif obsolete? and (use_instead != other.use_instead)
           if use_instead.nil?
             1
           elsif other.use_instead.nil?
             -1
           else
             use_instead <=> other.use_instead
           end
         else
           0
         end
  end

  pc
end

#registered=(v) ⇒ Object

:nodoc:



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

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.

Returns:

  • (Boolean)


367
368
369
370
371
372
373
374
# File 'lib/mime/type.rb', line 367

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

#signature=(v) ⇒ Object

:nodoc:



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

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

#signature?Boolean

Returns true when the simplified MIME::Type is in the list of known digital signatures.

Returns:

  • (Boolean)


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

def signature?
  !!@signature
end

#systemObject

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.



258
259
260
261
# File 'lib/mime/type.rb', line 258

def system
  MIME.deprecated(self, __method__)
  @system
end

#system=(os) ⇒ Object

:nodoc:



262
263
264
265
266
267
268
# File 'lib/mime/type.rb', line 262

def system=(os) # :nodoc:
  if os.nil? or os.kind_of?(Regexp)
    @system = os
  else
    @system = %r|#{os}|
  end
end

#system?Boolean

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

This method is deprecated.

Returns:

  • (Boolean)


405
406
407
408
# File 'lib/mime/type.rb', line 405

def system?
  MIME.deprecated(self, __method__)
  not @system.nil?
end

#to_aObject

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

This method is deprecated.



442
443
444
445
446
# File 'lib/mime/type.rb', line 442

def to_a
  MIME.deprecated(self, __method__)
  [ @content_type, @extensions, @encoding, @system, obsolete?, @docs,
    @references, 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.



472
473
474
# File 'lib/mime/type.rb', line 472

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.



452
453
454
455
456
457
458
459
460
461
462
463
# File 'lib/mime/type.rb', line 452

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

Converts the MIME::Type to a JSON string.



466
467
468
# File 'lib/mime/type.rb', line 466

def to_json(*args)
  to_h.to_json(*args)
end

#to_sObject

Returns the MIME::Type as a string.



426
427
428
# File 'lib/mime/type.rb', line 426

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


434
435
436
# File 'lib/mime/type.rb', line 434

def to_str
  @content_type
end

#urlObject

:nodoc:



305
306
307
308
# File 'lib/mime/type.rb', line 305

def url # :nodoc:
  MIME.deprecated(self, __method__, "and has been renamed to #references")
  references
end

#url=(r) ⇒ Object

:nodoc:



309
310
311
312
# File 'lib/mime/type.rb', line 309

def url=(r) # :nodoc:
  MIME.deprecated(self, __method__, "and has been renamed to #references=")
  self.references = r
end

#urlsObject

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 LTSW will be translated into:

http://www.ltsw.se/knbase/internet/<mediatype>.htp

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.



334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/mime/type.rb', line 334

def urls
  @references.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{^LTSW$}
      LTSW_URL % @media_type
    when %r{^\{([^=]+)=([^\}]+)\}}
      [$1, $2]
    when %r{^\[([^=]+)=([^\]]+)\]}
      [$1, CONTACT_URL % $2]
    when %r{^\[([^\]]+)\]}
      CONTACT_URL % $1
    else
      el
    end
  end
end