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.



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

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

Instance Attribute Details

#extensionsObject (readonly)

Returns the value of attribute extensions.



48
49
50
# File 'lib/utopia/static/mime_types.rb', line 48

def extensions
  @extensions
end

Class Method Details

.extensions_for(types, library = MIME_TYPES) ⇒ Object

Find extensions associated with the given MIME types.



54
55
56
57
58
# File 'lib/utopia/static/mime_types.rb', line 54

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:



63
64
65
66
67
68
69
70
71
72
73
# File 'lib/utopia/static/mime_types.rb', line 63

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.



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

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