Skip to content

Instantly share code, notes, and snippets.

@SSDany
Created October 18, 2009 15:01
Show Gist options
  • Save SSDany/212700 to your computer and use it in GitHub Desktop.
Save SSDany/212700 to your computer and use it in GitHub Desktop.
module MIMERegistry
REGISTRY = {}
EXTENSIONS = {}
module_function
# Registers the new MIME-Type and associated extensions.
# The first one of extensions will be treated as the 'preferred'
# for the MIME-Type.
#
def register(thing, *extensions)
return if extensions.empty?
extensions.map! { |ext| ext[0] == ?. ? ext.downcase : ".#{ext.downcase}" }
extensions.each { |ext| REGISTRY[ext] = thing }
EXTENSIONS[thing] = extensions.first
nil
end
def lookup(ext, fallback = 'application/octet-stream')
REGISTRY.fetch(ext[0] == ?. ? ext.downcase : ".#{ext.downcase}", fallback)
end
def extension_for(thing, fallback = nil)
EXTENSIONS.fetch thing, fallback
end
# Loads the set of MIME-Types from the Apache compatible mime.types file.
# original source: webrick.
def load_from(file)
open(file) do |io|
io.each do |line|
line.strip!
next if line.empty? || /^#/ === line
register *line.split(/\s+/)
end
end
true
end
end
# EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment