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.

'3.1'

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

Yields:

  • (_self)

Yield Parameters:

  • _self (MIME::Type)

    the object that the method was called on



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/mime/type.rb', line 87

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

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


192
193
194
# File 'lib/mime/type.rb', line 192

def content_type
  @content_type
end

#docsObject

The documentation for this MIME::Type.



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

def docs
  @docs
end

#encodingObject

Returns the value of attribute encoding.



283
284
285
# File 'lib/mime/type.rb', line 283

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


353
354
355
# File 'lib/mime/type.rb', line 353

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


206
207
208
# File 'lib/mime/type.rb', line 206

def media_type
  @media_type
end

#obsoleteObject Also known as: obsolete?

Returns true if the media type is obsolete.



317
318
319
# File 'lib/mime/type.rb', line 317

def obsolete
  @obsolete
end

#raw_media_typeObject (readonly)

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

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


212
213
214
# File 'lib/mime/type.rb', line 212

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


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

def raw_sub_type
  @raw_sub_type
end

#registeredObject Also known as: registered?

Indicates whether the MIME type has been registered with IANA.



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

def registered
  @registered
end

#signatureObject Also known as: signature?

Indicateswhether the MIME type is declared as a signature type.



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

def signature
  @signature
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  => x-chemical/x-pdb
audio/QCELP       => audio/qcelp


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

def simplified
  @simplified
end

#sub_typeObject (readonly)

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

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


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

def sub_type
  @sub_type
end

#use_insteadObject



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

def use_instead
  obsolete? ? @use_instead : nil
end

#xrefsObject

Returns the value of attribute xrefs.



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

def xrefs
  @xrefs
end

Class Method Details

.i18n_key(content_type) ⇒ Object

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



505
506
507
508
509
# 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) ⇒ Object

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



513
514
515
516
517
518
519
520
# 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

.simplified(content_type, remove_x_prefix: false) ⇒ Object

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.



499
500
501
# File 'lib/mime/type.rb', line 499

def simplified(content_type, remove_x_prefix: false)
  simplify_matchdata(match(content_type), remove_x_prefix)
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.



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

def <=>(other)
  if other.nil?
    -1
  elsif other.respond_to?(:simplified)
    simplified <=> other.simplified
  else
    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.



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

def add_extensions(*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)


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

def ascii?
  ASCII_ENCODINGS.include?(encoding)
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)


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

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)


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

def complete?
  !@extensions.empty?
end

#default_encodingObject

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



297
298
299
# File 'lib/mime/type.rb', line 297

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.



440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# 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.sort.to_a
      end
      coder['xrefs'] = hash
    end
  end
  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)


179
180
181
# File 'lib/mime/type.rb', line 179

def eql?(other)
  other.kind_of?(MIME::Type) and self == other
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.

:attr_accessor: extensions



232
233
234
# File 'lib/mime/type.rb', line 232

def extensions
  @extensions.to_a
end

#extensions=(value) ⇒ Object

:nodoc:



237
238
239
240
# File 'lib/mime/type.rb', line 237

def extensions=(value) # :nodoc:
  @extensions = Set[*Array(value).flatten.compact].freeze
  MIME::Types.send(:reindex_extensions, self)
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"


328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/mime/type.rb', line 328

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



470
471
472
473
474
475
476
477
478
479
480
481
482
483
# 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

#inspectObject

:nodoc:



485
486
487
488
489
# File 'lib/mime/type.rb', line 485

def inspect # :nodoc:
  # We are intentionally lying here because MIME::Type::Columnar is an
  # implementation detail.
  "#<MIME::Type: #{self}>"
end

#like?(other) ⇒ Boolean

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

Returns:

  • (Boolean)


113
114
115
116
117
118
119
120
# File 'lib/mime/type.rb', line 113

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

#preferred_extensionObject



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

def preferred_extension
  @preferred_extension || extensions.first
end

#preferred_extension=(value) ⇒ Object

:nodoc:



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

def preferred_extension=(value) # :nodoc:
  add_extensions(value) if value
  @preferred_extension = value
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.



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

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

#to_hObject

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



431
432
433
# File 'lib/mime/type.rb', line 431

def to_h
  encode_with({})
end

#to_json(*args) ⇒ Object

Converts the MIME::Type to a JSON string.



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

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

#to_sObject

Returns the MIME::Type as a string.



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

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


419
420
421
# File 'lib/mime/type.rb', line 419

def to_str
  content_type
end

#xref_urlsObject

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



375
376
377
378
379
380
# 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