Giter VIP home page Giter VIP logo

ruby-mime-types's Introduction

mime-types for Ruby

home

github.com/mime-types/ruby-mime-types/

code

github.com/mime-types/ruby-mime-types/

bugs

github.com/mime-types/ruby-mime-types/issues

rdoc

rdoc.info/gems/mime-types/

clog

github.com/mime-types/ruby-mime-types/blob/master/History.md

continuous integration

<img src=“https://github.com/mime-types/ruby-mime-types/actions/workflows/ci.yml/badge.svg” alt=“Build Status” />

test coverage

<img src=“https://coveralls.io/repos/mime-types/ruby-mime-types/badge.svg?branch=master&service=github” alt=“Coverage Status” />

Description

The mime-types library provides a library and registry for information about MIME content type definitions. It can be used to determine defined filename extensions for MIME types, or to use filename extensions to look up the likely MIME type definitions.

Version 3.0 is a major release that requires Ruby 2.0 compatibility and removes deprecated functions. The columnar registry format introduced in 2.6 has been made the primary format; the registry data has been extracted from this library and put into mime-types-data. Additionally, mime-types is now licensed exclusively under the MIT licence and there is a code of conduct in effect. There are a number of other smaller changes described in the History file.

About MIME Media Types

MIME content types are used in MIME-compliant communications, as in e-mail or HTTP traffic, to indicate the type of content which is transmitted. The mime-types library provides the ability for detailed information about MIME entities (provided as an enumerable collection of MIME::Type objects) to be determined and used. There are many types defined by RFCs and vendors, so the list is long but by definition incomplete; don’t hesitate to add additional type definitions. MIME type definitions found in mime-types are from RFCs, W3C recommendations, the IANA Media Types registry, and user contributions. It conforms to RFCs 2045 and 2231.

mime-types 3.x

Users are encouraged to upgrade to mime-types 3.x as soon as is practical. mime-types 3.x requires Ruby 2.0 compatibility and a simpler licensing scheme.

Synopsis

MIME types are used in MIME entities, as in email or HTTP traffic. It is useful at times to have information available about MIME types (or, inversely, about files). A MIME::Type stores the known information about one MIME type.

require 'mime/types'

plaintext = MIME::Types['text/plain'] # => [ text/plain ]
text = plaintext.first
puts text.media_type            # => 'text'
puts text.sub_type              # => 'plain'

puts text.extensions.join(' ')  # => 'txt asc c cc h hh cpp hpp dat hlp'
puts text.preferred_extension   # => 'txt'
puts text.friendly              # => 'Text Document'
puts text.i18n_key              # => 'text.plain'

puts text.encoding              # => quoted-printable
puts text.default_encoding      # => quoted-printable
puts text.binary?               # => false
puts text.ascii?                # => true
puts text.obsolete?             # => false
puts text.registered?           # => true
puts text.provisional?          # => false
puts text.complete?             # => true

puts text                       # => 'text/plain'

puts text == 'text/plain'       # => true
puts 'text/plain' == text       # => true
puts text == 'text/x-plain'     # => false
puts 'text/x-plain' == text     # => false

puts MIME::Type.simplified('x-appl/x-zip') # => 'x-appl/x-zip'
puts MIME::Type.i18n_key('x-appl/x-zip') # => 'x-appl.x-zip'

puts text.like?('text/x-plain') # => true
puts text.like?(MIME::Type.new('x-text/x-plain')) # => true

puts text.xrefs.inspect # => { "rfc" => [ "rfc2046", "rfc3676", "rfc5147" ] }
puts text.xref_urls # => [ "http://www.iana.org/go/rfc2046",
                    #      "http://www.iana.org/go/rfc3676",
                    #      "http://www.iana.org/go/rfc5147" ]

xtext = MIME::Type.new('x-text/x-plain')
puts xtext.media_type # => 'text'
puts xtext.raw_media_type # => 'x-text'
puts xtext.sub_type # => 'plain'
puts xtext.raw_sub_type # => 'x-plain'
puts xtext.complete? # => false

puts MIME::Types.any? { |type| type.content_type == 'text/plain' } # => true
puts MIME::Types.all?(&:registered?) # => false

# Various string representations of MIME types
qcelp = MIME::Types['audio/QCELP'].first # => audio/QCELP
puts qcelp.content_type         # => 'audio/QCELP'
puts qcelp.simplified           # => 'audio/qcelp'

xwingz = MIME::Types['application/x-Wingz'].first # => application/x-Wingz
puts xwingz.content_type        # => 'application/x-Wingz'
puts xwingz.simplified          # => 'application/x-wingz'

Columnar Store

mime-types uses as its primary registry storage format a columnar storage format reducing the default memory footprint. This is done by selectively loading the data on a per-attribute basis. When the registry is first loaded from the columnar store, only the canonical MIME content type and known extensions and the MIME type will be connected to its loading registry. When other data about the type is required (including preferred_extension, obsolete?, and registered?) that data is loaded from its own column file for all types in the registry.

The load of any column data is performed with a Mutex to ensure that types are updated safely in a multithreaded environment. Benchmarks show that while columnar data loading is slower than the JSON store, it cuts the memory use by a third over the JSON store.

If you prefer to load all the data at once, this can be specified in your application Gemfile as:

gem 'mime-types', require: 'mime/types/full'

Projects that do not use Bundler should require the same:

require 'mime/types/full'

Libraries that use mime-types are discouraged from choosing the JSON store.

For applications and clients that used mime-types 2.6 when the columnar store was introduced, the require used previously will still work through at least version 4 and possibly beyond; it is effectively an empty operation. You are recommended to change your Gemfile as soon as is practical.

require 'mime/types/columnar'

Note that MIME::Type::Columnar and MIME::Types::Columnar are considered private variant implementations of MIME::Type and MIME::Types and the specific implementation should not be relied upon by consumers of the mime-types library. Instead, depend on the public implementations (MIME::Type and MIME::Types) only.

Cached Storage

mime-types supports a cache of MIME types using Marshal.dump. The cache is invalidated for each version of the mime-types-data gem so that data version 3.2015.1201 will not be reused with data version 3.2016.0101. If the environment variable RUBY_MIME_TYPES_CACHE is set to a cache file, mime-types will attempt to load the MIME type registry from the cache file. If it cannot, it will load the types normally and then saves the registry to the cache file.

The caching works with both full stores and columnar stores. Only the data that has been loaded prior to saving the cache will be stored.

mime-types Modified Semantic Versioning

The mime-types library has one version number, but this single version number tracks both API changes and registry data changes; this is not wholly compatible with all aspects of Semantic Versioning; removing a MIME type from the registry could be considered a breaking change under some interpretations of semantic versioning (as lookups for that particular type would no longer work by default).

mime-types uses a modified semantic versioning scheme. Given the version MAJOR.MINOR:

  1. If an incompatible API (code) change is made, the MAJOR version will be incremented, MINOR will be set to zero, and PATCH will be reset to the implied zero.

  2. If an API (code) feature is added that does not break compatibility, the MINOR version will be incremented and PATCH will be reset to the implied zero.

  3. If there is a bugfix to a feature added in the most recent MAJOR.MINOR release, the implied PATCH value will be incremented resulting in MAJOR.MINOR.PATCH.

In practical terms, there will be fewer releases of mime-types focussing on features because of the existence of the mime-types-data gem, and if features are marked deprecated in the course of mime-types 3.x, they will not be removed until mime-types 4.x or possibly later.

Code of Conduct

Contributing

Licence

ruby-mime-types's People

Contributors

ab avatar ajvondrak avatar albus522 avatar ameuret avatar avgerin0s avatar blanquer avatar burke avatar byroot avatar cgat avatar chancancode avatar dillonwelch avatar edwardbetts avatar galfert avatar gogainda avatar graaff avatar halostatue avatar janko avatar jasnow avatar jeremyevans avatar juanitofatas avatar junaruga avatar keerthisiv avatar mishina2228 avatar olleolleolle avatar petergoldstein avatar postmodern avatar punkrats avatar sarahhodne avatar tenderlove avatar xentek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ruby-mime-types's Issues

Deprecated methods are used internally

I'm not sure if this is the right forum as this is really just a question, sorry if it's not.

I'm using this library, but I'm trying to canonicalize types, and I'm doing it thus:

def mime_types(type)
  if type == 'application/vnd.ms-excel'
    type = 'application/excel'
  end
  MIME::Types[type]
end

There's probably a much better way, but this works. The point of my question is that when I do this for the above type, I get two deprecation warnings:

MIME::Type#platform? is deprecated and will be removed.
MIME::Type#system? is deprecated and will be removed.

They appear to originate from calls within the library, so I'm wondering if I'm doing anything wrong or if the above method will cease to work in the future.

Thanks,

Matt Parlane

Installation Failed even ruby version is greater than 1.9.2

Hi,

I am new to ruby, trying to install rest-client, but it failed for mime types. Though my ruby version is greater than required version.

Installation Failed:

ruby -v
ruby 1.9.3p547 (2014-05-14 revision 45962) [x86_64-linux]

sudo gem install rest-client
ERROR: Error installing rest-client:
mime-types requires Ruby version >= 1.9.2.

Can not install mime-types 1.16

An error occurred while installing mime-types (1.16), and Bundler cannot continue.
Make sure that gem install mime-types -v '1.16' succeeds before bundling.

After this issue, I tried installing the versin 1.21 and it just works...
So I'm almost sure there is something weird with the 1.16 version.

undefined method `zero?' for nil:NilClass

When running this code

MIME::Types[/^image/]

with JRuby

lib/mime/types.rb line 93

    pc = if registered? != other.registered?
               registered? ? -1 : 1 # registered < unregistered
             elsif platform? != other.platform?
               platform? ? 1 : -1 # generic < platform
             elsif complete? != other.complete?
               pc = complete? ? -1 : 1 # complete < incomplete
             elsif obsolete? != other.obsolete?
               pc = obsolete? ? 1 : -1 # current < obsolete
             end

pc is nil and crashes on pc.zero?
MRI 1.9.3 and Rubinius works 100%, this is only on JRuby

Since nil.zero? is invalid on every implementation, I thought I'd make an issue here rather than JRuby. Unfortunately I don't understand exactly where the issue is.

Make RUBY_MIME_TYPES_LAZY_LOAD the default

Although loading the MIME type registry is fairly fast, do not force people to pay that cost up front. Implement ENV['RUBY_MIME_TYPES_LAZY_LOAD'] as the default behaviour and provide a new variable (ENV['RUBY_MIME_TYPES_IMMEDIATE_LOAD']) to fall back to the old behaviour.

Issue compiling mime-types in MacRuby

/Library/Ruby/Gems/MacRuby/0.12/gems/mime-types-1.22/lib/mime/types.rb:710:in block': regexp
\A
\s*
([])? # 0: Unregistered?
(!)? # 1: Obsolete?
(?:(\w+):)? # 2: Platform marker
(?-mix:([-\w.+]+)/([-\w.+]
))? # 3,4: Media type
(?:\s+@([^\s]+))? # 5: Extensions
(?:\s+:((?-mix:(?:base64|7bit|8bit|quoted-printable))))? # 6: Encoding
(?:\s+'(.+))? # 7: URL list
(?:\s+=(.+))? # 8: Documentation
(?:\s_([#]._)?)?
\s*
\z
' compilation error: U_REGEX_MISSING_CLOSE_BRACKET (RegexpError)
from /Library/Ruby/Gems/MacRuby/0.12/gems/mime-types-1.22/lib/mime/types.rb:600:in block' from /Library/Ruby/Gems/MacRuby/0.12/gems/mime-types-1.22/lib/mime/types.rb:575:inblock'
from /Library/Ruby/Gems/MacRuby/0.12/gems/mime-types-1.22/lib/mime/types.rb:4:in `

'

No entry for reg, ps1, vbs files

MIME::Types knows of bat, com, dll, exe, and msi as application/x-msdos-program, but has no entries for reg, ps1, or vbs files.

Could we add these to the same entry as bat/exe/msi?

Semantic Versioning

It would be great if mime-types switched to semantic versioning:
http://semver.org/

Currently versions look like 1.25.
I'm not sure if that's equivalent to 1.25.0 or 1.1.25.
Put another way, I don't know if 1.23 -> 1.25 introduces new features, or strictly bug fixes.

1.17.1 breaks on heroku

The app is running on 1.9.2 and breaks with this error:

 /app/.bundle/gems/ruby/1.9.1/bundler/gems/mime-types-e91e71215cad/lib/mime/types.rb:755:in `split': invalid byte sequence in US-ASCII (ArgumentError)

I managed to downgrade to 1.16 which runs fine.

RubyForge is shutting down

Make sure there are no more references to rubyforge and that the documentation is safely located elsewhere.

Additional mime types for fonts, coffescript and air

We're currently using mime-types in our app and added the following additional content types:

MIME::Type.new('text/x-coffeescript') do |t|
  t.extensions = %w(coffee)
  t.encoding   = '8bit'
end,

MIME::Type.new('application/x-font-truetype') do |t|
  t.extensions  = %w(ttf)
  t.encoding    = 'base64'
end,

MIME::Type.new('application/x-woff') do |t|
  t.extensions  = %w(woff)
  t.encoding    = 'base64'
end

MIME::Type.new('application/vnd.adobe.air-applicationinstaller-package+zip') do |t|
  t.extensions  = %w(air)
  t.encoding    = 'base64'
end

I think those make sense to add as a default, but I wanted to make sure you agree before I go ahead and create/send a pull request.

Mime::Type extension order changed (.jpg)

Hello,

The following code used to return jpg but now returns jpe since a recent upgrade (the offending commit is 60f478c#diff-a391e22c04309238b0bd982369bcfa4fR103)

2.1.1 :003 > MIME::Types.type_for("foo.jpg").first.extensions.first
 => "jpe"

This is a problem because of https://github.com/thoughtbot/paperclip/blob/master/lib/paperclip/interpolations.rb#L119-122 which now stores jpegs with a .jpe extension.

I think the library should provide a way to provide a "prefered" extension for a content-type.

Semantic versioning

Is it possible you can use semantic versioning, e.g. $major.$minor.$patch in your releases?

Invalid characters in documentation

Clean install of Rails 3 on Ubuntu 10.04 LTS, using Ruby 1.9.3p194. System locale is UTF-8.

Installing ri documentation for mime-types-1.19...
unable to convert U+2013 from UTF-8 to US-ASCII for lib/mime/types.rb, skipping
unable to convert "\xC3" to UTF-8 in conversion from ASCII-8BIT to UTF-8 to US-ASCII for lib/mime/types/application, skipping
unable to convert "\xC3" to UTF-8 in conversion from ASCII-8BIT to UTF-8 to US-ASCII for History.rdoc, skipping
unable to convert "\xE2" to UTF-8 in conversion from ASCII-8BIT to UTF-8 to US-ASCII for Licence.rdoc, skipping

Verifying the first error:

$ cd mime-types-1.19/lib/mime/
$ head -1 types.rb
# -*- ruby encoding: utf-8 -*-
$ uconv -f utf-8 types.rb > /dev/null
Conversion from Unicode to codepage failed at input byte position 19951. Unicode: 2013 Error: Invalid character found

Seems to be an error in the comments, but I thought I'd let you know about it.

Rdoc 3.9.4, RubyGems 1.8.23.

add webm and ogg support

mime-type should set the right mime-types for webm and ogg

it is strange, but this bug should be fixed but i can not find any branch where it is ..

it was fixed in this commit:
c4db3a6

in which branch is it, it should be in master.. no?

JSON is not binary

JSON should not be binary?. It is written and stored as plain text, usually ASCII or UTF-8.

BSON is binary.

invalid gem: tar is corrupt, name contains null byte

Installing rails via rvm error:
Successfully installed activeresource-3.2.12
Fetching: mime-types-1.21.gem (100%)
ERROR: Error installing rails:
invalid gem: tar is corrupt, name contains null byte in /Users/xxx/.rvm/gems/ruby-2.0.0-p0/cache/mime-types-1.21.gem

Releasing 1.17.2

Hey guys,

Are you releasing 1.17.2 anytime soon? 1.17.1 is breaking stuff that you've already fixed and just merged into master for Padrino, Rails and perhaps some other frameworks that depend on your lib out there.

Thanks! :)
Darío

Issue mail & mimetype

Within my Ruby hyla application, I would like to use mailand mime-types. They have been declared in the gemspec file

Gem::Specification.new do |s|
...
s.add_runtime_dependency 'mail', '~> 2.5.4'
s.add_runtime_dependency 'mime-types', '~> 1.16'

but when I launch a Ruby class to send a mail

module Hyla
  class Sendmail
    require 'mail'
    require 'mime/types'
    mail = Mail.new do

I get a cannot load such a file -- mime/types

/Users/chmoulli/.rbenv/versions/1.9.3-p484/bin/ruby -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift)     /Users/chmoulli/MyProjects/hyla/lib/hyla/send_mail.rb
/Users/chmoulli/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/mail-2.5.4/lib/mail.rb:9:in `require': cannot load such file -- mime/types (LoadError)
    from /Users/chmoulli/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/mail-2.5.4/lib/mail.rb:9:in `<module:Mail>'
    from /Users/chmoulli/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/mail-2.5.4/lib/mail.rb:2:in `<top (required)>'
    from /Users/chmoulli/MyProjects/hyla/lib/hyla/send_mail.rb:4:in `require'

My issue has been reported here : mikel/mail#654

but until now I'm blocked and don't know what to do to resolve the problem

Provide logical categories for mime-types for convenience.

As per the discussion in socketry/utopia#1

It would be good if MIME::Types.of(:archive) would provide common, non-obsolete archive types.

In addition, providing a way to expand mime types based on a standard format might be nice, e.g. something similar to

MIME_TYPES = {
  :xiph => {
    "ogx" => "application/ogg",
    "ogv" => "video/ogg",
    "oga" => "audio/ogg",
    "ogg" => "audio/ogg",
    "spx" => "audio/ogg",
    "flac" => "audio/flac",
    "anx" => "application/annodex",
    "axa" => "audio/annodex",
    "xspf" => "application/xspf+xml",
  },
  :media => [
    :xiph, "mp3", "mp4", "wav", "aiff", ["aac", "audio/x-aac"], "mov", "avi", "wmv", "mpg"
    ],
  :text => [
    "html", "css", "js", "txt", "rtf", "xml", "pdf"
    ],
  :fonts => [
    "otf", ["eot", "application/vnd.ms-fontobject"], "ttf", "woff"
    ],
  :archives => [
    "zip", "tar", "tgz", "tar.gz", "tar.bz2", ["dmg", "application/x-apple-diskimage"],
  ["torrent", "application/x-bittorrent"]
    ],
  :images => [
    "png", "gif", "jpeg", "tiff", "svg"
    ],
  :default => [
    :media, :text, :archives, :images, :fonts
    ]
}

Being able to write:

MIME::Types.expand(MIME_TYPES) {|type| ... }

Could be very useful. Propose that we use a similar method for expansion, based on Utopia, the code here: https://github.com/ioquatix/utopia/blob/master/lib/utopia/middleware/static.rb#L160-L200

def load_mime_types(types)
  result = {}

  extract_extensions = lambda do |mime_type|
  # LOG.info "Extracting #{mime_type.inspect}"
  mime_type.extensions.each{|ext| result["." + ext] = mime_type.content_type}
  end

  types.each do |type|
    current_count = result.size
    # LOG.info "Processing #{type.inspect}"

    begin
      case type
      when Symbol
        result = load_mime_types(MIME_TYPES[type]).merge(result)
      when Array
        result["." + type[0]] = type[1]
      when String
        mt = MIME::Types.of(type).select{|mt| !mt.obsolete?}.each do |mt|
          extract_extensions.call(mt)
        end
      when Regexp
        MIME::Types[type].select{|mt| !mt.obsolete?}.each do |mt|
          extract_extensions.call(mt)
        end
      when MIME::Type
        extract_extensions.call(type)
      end
    rescue
      LOG.error "#{self.class.name}: Error while processing #{type.inspect}!"
      raise $!
    end

    if result.size == current_count
      LOG.warn "#{self.class.name}: Could not find any mime type for #{type.inspect}"
    end
  end

  return result
end

In addition, allowing a user to customise the way this expansion work could be a good idea to ensure that a user can lock in specific behaviour. But then alternatively, the user could lock in a specific version of mime-types gem which would serve the same purpose. However, it should still be possible for the user to adjust the way expansions works by appending or amending types as required.

omit setup.rb from gem

Please consider omitting setup.rb from the packaged gem. It is LGPL licensed, while the rest of the package is available under the Ruby, Perl Artistic, or GPL2 licenses. It would be simpler to have uniform licensing for the entire package.

Online documentation has lame interpolation failures

At http://mime-types.rubyforge.org/MIME/Types.html#method-i-type_for there is sample code which looks like

puts "MIME::Types.type_for('citydesk.xml')
  => "#{MIME::Types.type_for('citydesk.xml')}"
puts "MIME::Types.type_for('citydesk.gif')
  => "#{MIME::Types.type_for('citydesk.gif')}"

Seriously? It's supposed to output a bunch of junk with a #{} around it? I don't think so.
Unfortunately, because the real sample output was missing when I looked, I assumed it would return a single type and tried to send something from Rails with :content_type => MIME::Types.type_for('foo.css') which sent the deceptively-good-looking string [text/css] instead of sending text/css. I subsequently wasted a bunch of time tracking down what the problem was.

mime-types 1.17.2 fails tests with ruby 1.8.7

When I try to run the tests with ruby 1.8.7 I get the following failure:

  1) Failure:
test_platform_eh(TestMIME_Type) [./test/test_mime_type.rb:182]:
Failed refutation, no message given

33 tests, 139 assertions, 1 failures, 0 errors, 0 skips

Consider switching to YAML or CSV

Consider storing your type lists in YAML or CSV. This would make it easier to edit in the future. It took me a while to understand the structure of your type lists.

Provide MIME::Type#add_extensions

Code like this

  extensions.each { |ext|
    type.extensions << ext unless type.extensions.include?( ext )
  }

should not be necessary. It should be possible to do:

  type.add_extensions(extensions)

and have the values be uniquely represented.

Internally, it would combine the extensions array and call Array#uniq! on it. The return value would be the full list of extensions.

Strange behavior (everything ok on `pry` but not loading database on `irb`)

Whenever I do the following on pry things go as expected:

> require 'mime-types'
> MIME::Types.of 'test.png'
# output
@simplified="image/png"
>

But when I do the exact same on irb (or in any script per se), it returns an empty array:

> require 'mime-types'
> MIME::Types.of 'test.png'
[]
>

Even the following doesn't work:

ruby -rmime-types -e "puts MIME::Types.of('test.png')"

Include the public cert?...

The gem mime-types-2.4.3 can't be installed because the security policy didn't allow it, with the message: root cert /CN=austin/DC=rubyforge/DC=org is not trusted

When installing mime-types using high security, I am notified that version 2.4.3 cannot be installed because of an untrusted cert, but I can find no trace of the public cert. Did I miss it?

missing key

Using mime-types (1.16) from http://github.com/halostatue/mime-types.git (at master) /Users/myaccount/.rvm/rubies/ree-1.8.7-2010.02/lib/ruby/site_ruby/1.8/rubygems/security.rb:759:in `read': No such file or directory - /Users/austin/.gem/gem-private_key.pem (Errno::ENOENT)

Missing extensions

Hi,

I have an issue with some content types which don't always return an extension. My example is "video/mp4", which has no extension although the RFC (RFC4337) lists both "mp4" and "mpg4" as registered extensions.
My use case is: I download an attachment with an "obscured" URL (like "test.com/videos/sha1"), and I use a mime-type to help build a file name.
I don't know if all mime-types are supposed to have 1+ extension (ex: H264), but there are some which obviously miss an extension (at least, that's what I understand). If intentional, should I work with the mime-type's sub_type to choose a file extension is the library doens't provide an extension?

Thanks,
Florent.

MIME::Types#add_type will add exact duplicate objects

The type variants and extension index code contains Array objects, not Set objects, which means that you can do:

text = MIME::Type['text/plain'].first
types = MIME::Types.new
types.add(text, text)

Text will be listed in the lookup fields twice.

Feature request: support tree, suffix, and parameters (RFC 6838/6839 and others)

mime-types was "built to conform to the MIME types of RFCs 2045 and 2231". RFC 2045 is itself composed of many other RFCs, some of which have been obsoleted or updated. For example, it refers to RFC 2048 - Multipurpose Internet Mail Extensions (MIME) Part Four: Registration Procedures (which defined the vendor tree). That RFC was obsoleted by RFC 4288 and 4289. RFC 4288 in turn was obsoleted by RFC 6838.

In short, too many RFCs to keep track of, but Wikipedia's summary is pretty good.

These newer RFCs have introduced or standardized three important concepts - tree, suffix, and parameters. The structure of a mime-type name is:
top-level type name / [ tree. ] subtype name [ +suffix ] [ ; parameters ]

These are concepts are commonly used by modern applications. Parameters are often used to define charsets or codecs for videos:

text/plain; charset=utf-8
video/mp4; codecs="avc1.640028"

Suffix is used to indicate an underlying structure or container format. The following suffixes are registered: +xml, +json, +ber, +der, +fastinfoset, +wbxml, +zip, and +cbor. Some examples include SVG images or Atom feeds, which are their own registered format but use XML as the underlying structure:

image/svg+xml
application/atom+xml

The vendor tree is commonly used by RESTful services, especially in combination with a +suffix. GitHub APIs, for example, return the following mime-types:

application/json
application/vnd.github+json
application/vnd.github.v3+json
application/vnd.github.v3.raw+json
application/vnd.github.v3.text+json
application/vnd.github.v3.html+json
application/vnd.github.v3.full+json
application/vnd.github.v3.diff
application/vnd.github.v3.patch

It would be nice if mime-types supported these concepts. I'm not sending a PR yet because exactly what "support" looks like probably requires some discussion. I think the tree is simple and would just be an (optional) part, like sub_type or media_type. The suffix concept may also be similar, though I think it'd be useful if it was used for inheritable default values (e.g. if MIME::Types['application/vnd.github+json+json'] returned an unregistered type based on application/json, rather than returning nothing). The parameters concept is probably the one that needs the most thought, because right now they're ignored during lookup but no while creating types:

MIME::Type.new('text/plain; charset=utf-8') == MIME::Type.new('text/plain; charset=ascii')
# => false
MIME::Types['text/plain; charset=utf-8'] == MIME::Types['text/plain; charset=ascii']
# => true

Bad UTF-8 characters in rdoc

Installing RDoc documentation for mime-types-1.18...
unable to convert "\xC3" to UTF-8 in conversion from ASCII-8BIT to UTF-8 to US-ASCII for lib/mime/types/application, skipping
unable to convert "\xC3" to UTF-8 in conversion from ASCII-8BIT to UTF-8 to US-ASCII for History.rdoc, skipping
unable to convert "\xE2" to UTF-8 in conversion from ASCII-8BIT to UTF-8 to US-ASCII for Licence.rdoc, skipping
unable to convert "\xC3" to UTF-8 in conversion from ASCII-8BIT to UTF-8 to US-ASCII for type-lists/application.txt, skipping
Installing RDoc documentation for diff-lcs-1.1.3...
unable to convert "\xE2" to UTF-8 in conversion from ASCII-8BIT to UTF-8 to US-ASCII for License.rdoc, skipping

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.