Retrieving a sensible file extension for a given MIME string in Rails

Here’s a little snippet of code to retrieve a sensible file extension based on a MIME string, using the built-in MIME dictionary in Rails 

  module Mime
class Type
class << self
# Lookup, guesstimate if fail, the file extension
# for a given mime string. For example:
# >> Mime::Type.file_extension_of 'text/rss+xml'
# => "xml"
def file_extension_of(mime_string)
set = Mime::LOOKUP[mime_string]
sym = set.instance_variable_get("@symbol") if set
return sym.to_s if sym
return $1 if mime_string =~ /(\w+)$/

As mentioned in the comments in the code, you can now give it Mime::Type.file_extension_of text/rss+xmland it will return you "xml". Any extension missing, just apply the standard Rails MIME registration steps

  Mime::Type.register "text/", :jad
Mime::Type.file_extension_of "text/" # => "jad"

The bonus with using the standard Mime::Type.register is that both your MIME lookup and respond_to gets smarter together.