Class: HTTP::Accept::MediaTypes::Map

Inherits:
Object
  • Object
show all
Defined in:
lib/http/accept/media_types/map.rb

Overview

Map a set of mime types to objects.

Constant Summary collapse

WILDCARD =
"*/*".freeze

Instance Method Summary collapse

Constructor Details

#initializeMap

Returns a new instance of Map.



13
14
15
# File 'lib/http/accept/media_types/map.rb', line 13

def initialize
	@media_types = {}
end

Instance Method Details

#<<(object) ⇒ Object

Add a converter to the collection. A converter can be anything that responds to #content_type. Objects will be considered in the order they are added, subsequent objects cannot override previously defined media types. ‘object` must respond to #split(’/‘, 2) which should give the type and subtype.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/http/accept/media_types/map.rb', line 51

def << object
	type, subtype = object.split('/', 2)
	
	# We set the default if not specified already:
	@media_types[WILDCARD] = object if @media_types.empty?
	
	if type != '*'
		@media_types["#{type}/*"] ||= object
		
		if subtype != '*'
			@media_types["#{type}/#{subtype}"] ||= object
		end
	end
	
	return self
end

#[](media_range) ⇒ Object



46
47
48
# File 'lib/http/accept/media_types/map.rb', line 46

def [] media_range
	@media_types[media_range]
end

#[]=(media_range, object) ⇒ Object



42
43
44
# File 'lib/http/accept/media_types/map.rb', line 42

def []= media_range, object
	@media_types[media_range] = object
end

#for(media_types) ⇒ Object

Given a list of content types (e.g. from browser_preferred_content_types), return the best converter. Media types can be an array of MediaRange or String values.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/http/accept/media_types/map.rb', line 27

def for(media_types)
	media_types.each do |media_range|
		mime_type = case media_range
			when String then media_range
			else media_range.mime_type
		end
		
		if object = @media_types[mime_type]
			return object, media_range
		end
	end
	
	return nil
end

#freezeObject



17
18
19
20
21
22
23
24
# File 'lib/http/accept/media_types/map.rb', line 17

def freeze
	unless frozen?
		@media_types.freeze
		@media_types.each{|key,value| value.freeze}
		
		super
	end
end