Class: MimeTypeSet

Inherits:
Object
  • Object
show all
Defined in:
lib/yodel/mime_types/mime_type_set.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeMimeTypeSet

Returns a new instance of MimeTypeSet.



3
4
5
6
7
8
# File 'lib/yodel/mime_types/mime_type_set.rb', line 3

def initialize
  @default = nil    # default mime type when no other can be matched
  @types = {}       # index by type name (:html)
  @extensions = {}  # index by type extensions (html, htm)
  @mime_types = {}  # index by mime types (text/html)
end

Instance Attribute Details

#typesObject

Returns the value of attribute types.



2
3
4
# File 'lib/yodel/mime_types/mime_type_set.rb', line 2

def types
  @types
end

Instance Method Details

#<<(type) ⇒ Object



20
21
22
23
24
25
# File 'lib/yodel/mime_types/mime_type_set.rb', line 20

def <<(type)
  @default ||= type
  @types[type.name] = type
  type.extensions.each {|extension| @extensions[extension] = type}
  type.mime_types.each {|mime_type| @mime_types[mime_type] = type}
end

#[](name) ⇒ Object



16
17
18
# File 'lib/yodel/mime_types/mime_type_set.rb', line 16

def [](name)
  @types[name]
end

#eachObject



10
11
12
13
14
# File 'lib/yodel/mime_types/mime_type_set.rb', line 10

def each
  @types.values.each do |type|
    yield type
  end
end

#mime_type_for_request(format, accept) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/yodel/mime_types/mime_type_set.rb', line 27

def mime_type_for_request(format, accept)
  # try to match by file extension first
  return @extensions[format] if format && @extensions.has_key?(format)
  
  # parse the accept string and try to match by mime type. The accept
  # header looks like: application/xml,text/html;q=0.9
  accept.to_s.split(',').each do |mime_type|
    name = mime_type.split(';').first
    return @mime_types[name] if @mime_types.has_key?(name)
  end
  
  # as a last resort, respond with the first mime type defined
  @default
end