class MimeTypeLoader

A class to assist with loading mime-type metadata.

Classes and Modules

class ExpansionError < ArgumentError

Raised when expansion processing fails.

Definitions

def initialize(library)

Initialize an empty extension map backed by named MIME type groups.

Signature

parameter library Object

The library.

Implementation

def initialize(library)
	@extensions = {}
	@library = library
end

def self.extensions_for(types, library = MIME_TYPES)

Find extensions associated with the given MIME types.

Signature

parameter types Array

The MIME type definitions to expand.

parameter library Hash

The named MIME type groups.

returns Hash(String, String)

A mapping from file extensions to content types.

Implementation

def self.extensions_for(types, library = MIME_TYPES)
	loader = self.new(library)
	loader.expand(types)
	return loader.extensions
end

def add_extension(extension)

Add an extension using its registered media type.

Signature

parameter extension String

The file extension.

returns Protocol::Media::Registry::Record

The registered media type record.

Implementation

def add_extension(extension)
	# Normalize optional leading dots and case before constructing the File.extname-style key:
	extension = extension.delete_prefix(".").downcase
	
	if record = Protocol::Media::Registry.for_extension(extension)
		@extensions["." + extension] = record.type.to_s
		return record
	end
	
	raise ExpansionError.new("Unknown file extension: #{extension.inspect}")
end

def expand(types)

Expand named groups, file extensions, and explicit extension pairs into extension mappings.

Signature

parameter types Array

The MIME type definitions.

returns Array

The supplied definitions.

raises ExpansionError

If a definition cannot be expanded.

Implementation

def expand(types)
	types.each do |type|
		case type
		when Symbol
			self.expand(@library.fetch(type))
		when Array
			@extensions["." + type[0]] = type[1]
		when String
			self.add_extension(type)
		else
			raise ExpansionError.new("Unsupported MIME type definition: #{type.inspect}")
		end
	rescue ExpansionError
		raise
	rescue
		raise ExpansionError.new("#{self.class.name}: Error while processing #{type.inspect}!")
	end
end