Class: Utopia::Static::MimeTypeLoader

Inherits:
Object
  • Object
show all
Defined in:
lib/utopia/static/mime_types.rb

Overview

A class to assist with loading mime-type metadata.

Defined Under Namespace

Classes: ExpansionError

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(library) ⇒ MimeTypeLoader

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



40
41
42
43
# File 'lib/utopia/static/mime_types.rb', line 40

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

Instance Attribute Details

#extensionsObject (readonly)

Returns the value of attribute extensions.



45
46
47
# File 'lib/utopia/static/mime_types.rb', line 45

def extensions
  @extensions
end

Class Method Details

.extensions_for(types, library = MIME_TYPES) ⇒ Object

Find extensions associated with the given MIME types.



51
52
53
54
55
# File 'lib/utopia/static/mime_types.rb', line 51

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

Instance Method Details

#add_extension(extension) ⇒ Object

Add an extension using its registered media type.

Raises:



60
61
62
63
64
65
66
67
68
69
70
# File 'lib/utopia/static/mime_types.rb', line 60

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

#expand(types) ⇒ Object

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



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/utopia/static/mime_types.rb', line 80

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