Class: MIME::Type

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/s33r/mimetypes.rb

Overview

The definition of one MIME content-type.

Usage

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 == 'text/plain'       # => true
puts MIME::Type.simplified('x-appl/x-zip') # => 'appl/zip'

Constant Summary collapse

VERSION =
'1.15'
MEDIA_TYPE_RE =

:nodoc:

%r{([-\w.+]+)/([-\w.+]*)}o
UNREG_RE =

:nodoc:

%r{[Xx]-}o
ENCODING_RE =

:nodoc:

%r{(?:base64|7bit|8bit|quoted\-printable)}o
PLATFORM_RE =

:nodoc:

%r|#{RUBY_PLATFORM}|o
SIGNATURES =
%w(application/pgp-keys application/pgp
application/pgp-signature application/pkcs10
application/pkcs7-mime application/pkcs7-signature
text/vcard)
IANA_URL =

:nodoc:

"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.

Yields:

  • (_self)

Yield Parameters:

  • _self (MIME::Type)

    the object that the method was called on



365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/s33r/mimetypes.rb', line 365

def initialize(content_type) #:yields self:
  matchdata = MEDIA_TYPE_RE.match(content_type)

  if matchdata.nil?
    raise InvalidContentType, "Invalid Content-Type provided ('#{content_type}')"
  end

  @content_type = content_type
  @raw_media_type = matchdata.captures[0]
  @raw_sub_type = matchdata.captures[1]

  @simplified = MIME::Type.simplified(@content_type)
  matchdata = MEDIA_TYPE_RE.match(@simplified)
  @media_type = matchdata.captures[0]
  @sub_type = matchdata.captures[1]

  self.extensions   = nil
  self.encoding     = :default
  self.system       = nil
  self.registered   = true

  yield self if block_given?
end

Instance Attribute Details

#content_typeObject (readonly)

Returns the whole MIME content-type string.

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


89
90
91
# File 'lib/s33r/mimetypes.rb', line 89

def content_type
  @content_type
end

#default_encodingObject (readonly)

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



163
164
165
# File 'lib/s33r/mimetypes.rb', line 163

def default_encoding
  @default_encoding
end

#docsObject

The documentation for this MIME::Type. Documentation about media types will be found on a media type definition as a comment. Documentation will be found through #docs.



189
190
191
# File 'lib/s33r/mimetypes.rb', line 189

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.



138
139
140
# File 'lib/s33r/mimetypes.rb', line 138

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 and nil values removed.



122
123
124
# File 'lib/s33r/mimetypes.rb', line 122

def extensions
  @extensions
end

#media_typeObject (readonly)

Returns the media type of the simplified MIME type.

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


94
95
96
# File 'lib/s33r/mimetypes.rb', line 94

def media_type
  @media_type
end

#obsolete=(value) ⇒ Object (writeonly)

Sets the obsolescence indicator for this media type.



184
185
186
# File 'lib/s33r/mimetypes.rb', line 184

def obsolete=(value)
  @obsolete = value
end

#raw_media_typeObject (readonly)

Returns the media type of the unmodified MIME type.

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


99
100
101
# File 'lib/s33r/mimetypes.rb', line 99

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


109
110
111
# File 'lib/s33r/mimetypes.rb', line 109

def raw_sub_type
  @raw_sub_type
end

#registered=(value) ⇒ Object (writeonly)

:nodoc:



401
402
403
# File 'lib/s33r/mimetypes.rb', line 401

def registered=(value)
  @registered = value
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


118
119
120
# File 'lib/s33r/mimetypes.rb', line 118

def simplified
  @simplified
end

#sub_typeObject (readonly)

Returns the sub-type of the simplified MIME type.

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


104
105
106
# File 'lib/s33r/mimetypes.rb', line 104

def sub_type
  @sub_type
end

#systemObject

The regexp for the operating system that this MIME::Type is specific to.



152
153
154
# File 'lib/s33r/mimetypes.rb', line 152

def system
  @system
end

#urlObject

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



204
205
206
# File 'lib/s33r/mimetypes.rb', line 204

def url
  @url
end

#use_insteadObject (readonly)

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.



172
173
174
# File 'lib/s33r/mimetypes.rb', line 172

def use_instead
  @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


276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/s33r/mimetypes.rb', line 276

def from_array(*args) #:yields MIME::Type.new:
  # Dereferences the array one level, if necessary.
  args = args[0] if args[0].kind_of?(Array)

  if args.size.between?(1, 8)
    m = MIME::Type.new(args[0]) do |t|
      t.extensions  = args[1] if args.size > 1
      t.encoding    = args[2] if args.size > 2
      t.system      = args[3] if args.size > 3
      t.obsolete    = args[4] if args.size > 4
      t.docs        = args[5] if args.size > 5
      t.url         = args[6] if args.size > 6
      t.registered  = args[7] if args.size > 7
    end
    yield m if block_given?
  else
    raise ArgumentError, "Array provided must contain between one and eight elements."
  end
  m
end

.from_hash(hash) {|m| ... } ⇒ 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

Yields:

  • (m)


319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/s33r/mimetypes.rb', line 319

def from_hash(hash) #:yields MIME::Type.new:
  type = {}
  hash.each_pair do |k, v| 
    type[k.to_s.tr('-A-Z', '_a-z').to_sym] = v
  end

  m = 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]
  end

  yield m if block_given?
  m
end

.from_mime_type(mime_type) {|m| ... } ⇒ 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

Yields:

  • (m)


350
351
352
353
354
355
356
357
358
# File 'lib/s33r/mimetypes.rb', line 350

def from_mime_type(mime_type) #:yields the new MIME::Type:
  m = MIME::Type.new(mime_type.content_type.dup) do |t|
    t.extensions = mime_type.extensions.dup
    t.system = mime_type.system.dup
    t.encoding = mime_type.encoding.dup
  end

  yield m if block_given?
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.



249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/s33r/mimetypes.rb', line 249

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

  if matchdata.nil?
    simplified = nil
  else
    media_type = matchdata.captures[0].downcase.gsub(UNREG_RE, '')
    subtype = matchdata.captures[1].downcase.gsub(UNREG_RE, '')
    simplified = "#{media_type}/#{subtype}"
  end
  simplified
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).



69
70
71
72
73
74
75
76
77
# File 'lib/s33r/mimetypes.rb', line 69

def <=>(other) #:nodoc:
  if other.respond_to?(:content_type)
    @content_type.downcase <=> other.content_type.downcase
  elsif other.respond_to?(:to_s)
    @simplified <=> Type.simplified(other.to_s)
  else
    @content_type.downcase <=> other.downcase
  end
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)


413
414
415
# File 'lib/s33r/mimetypes.rb', line 413

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)


406
407
408
# File 'lib/s33r/mimetypes.rb', line 406

def binary?
  @encoding == 'base64'
end

#complete?Boolean

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

Returns:

  • (Boolean)


436
437
438
# File 'lib/s33r/mimetypes.rb', line 436

def complete?
  not @extensions.empty?
end

#eql?(other) ⇒ Boolean

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

Returns:

  • (Boolean)


81
82
83
# File 'lib/s33r/mimetypes.rb', line 81

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

#like?(other) ⇒ Boolean

Returns true if the simplified type matches the current

Returns:

  • (Boolean)


58
59
60
61
62
63
64
# File 'lib/s33r/mimetypes.rb', line 58

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

#obsolete?Boolean

Returns true if the media type is obsolete.

Returns:

  • (Boolean)


180
181
182
# File 'lib/s33r/mimetypes.rb', line 180

def obsolete?
  @obsolete ? true : false
end

#platform?Boolean

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

Returns:

  • (Boolean)


430
431
432
# File 'lib/s33r/mimetypes.rb', line 430

def platform?
  system? and (RUBY_PLATFORM =~ @system)
end

#registered?Boolean

MIME content-types which are not regestered by IANA nor defined in RFCs are required to start with x-. This counts as well for a new media type as well as a new sub-type of an existing media type. If either the media-type or the content-type begins with x-, this method will return false.

Returns:

  • (Boolean)


394
395
396
397
398
399
400
# File 'lib/s33r/mimetypes.rb', line 394

def registered?
  if (@raw_media_type =~ UNREG_RE) || (@raw_sub_type =~ UNREG_RE)
    false
  else
    @registered
  end
end

#signature?Boolean

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

Returns:

  • (Boolean)


419
420
421
# File 'lib/s33r/mimetypes.rb', line 419

def signature?
  SIGNATURES.include?(@simplified.downcase)
end

#system?Boolean

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

Returns:

  • (Boolean)


424
425
426
# File 'lib/s33r/mimetypes.rb', line 424

def system?
  not @system.nil?
end

#to_aObject

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



452
453
454
455
# File 'lib/s33r/mimetypes.rb', line 452

def to_a
  [ @content_type, @extensions, @encoding, @system, @obsolete, @docs,
    @url, registered? ]
end

#to_hashObject

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



459
460
461
462
463
464
465
466
467
468
469
# File 'lib/s33r/mimetypes.rb', line 459

def to_hash
  { 'Content-Type'              => @content_type,
    'Content-Transfer-Encoding' => @encoding,
    'Extensions'                => @extensions,
    'System'                    => @system,
    'Obsolete'                  => @obsolete,
    'Docs'                      => @docs,
    'URL'                       => @url,
    'Registered'                => registered?,
  }
end

#to_sObject

Returns the MIME type as a string.



441
442
443
# File 'lib/s33r/mimetypes.rb', line 441

def to_s
  @content_type
end

#to_strObject

Returns the MIME type as a string for implicit conversions.



446
447
448
# File 'lib/s33r/mimetypes.rb', line 446

def to_str
  @content_type
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 #url, which always returns an array.



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/s33r/mimetypes.rb', line 224

def urls
  @url.map { |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{^\[([^\]]+)\]}
      CONTACT_URL % $1
    else
      el
    end
  }
end