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

Inherits:
Object
  • Object
show all
Defined in:
lib/http/accept/media_types.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.



38
39
40
41
42
43
# File 'lib/http/accept/media_types.rb', line 38

def initialize
	@media_types = Hash.new{|h,k| h[k] = {}}
	
	# Primarily for implementing #freeze efficiently.
	@all = []
end

Instance Method Details

#<<(object) ⇒ Object

Add a converter to the collection. A converter can be anything that responds to #content_type.



69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/http/accept/media_types.rb', line 69

def << object
	type, subtype = object.content_type.split('/')
	
	if @media_types.empty?
		@media_types[WILDCARD][WILDCARD] = object
	end
	
	if @media_types[type].empty?
		@media_types[type][WILDCARD] = object
	end
	
	@media_types[type][subtype] = object
	@all << object
end

#for(media_types) ⇒ Object

Given a list of content types (e.g. from browser_preferred_content_types), return the best converter.



56
57
58
59
60
61
62
63
64
65
66
# File 'lib/http/accept/media_types.rb', line 56

def for(media_types)
	media_types.each do |media_range|
		type, subtype = media_range.split
		
		if object = @media_types[type][subtype]
			return object, media_range
		end
	end
	
	return nil
end

#freezeObject



45
46
47
48
49
50
51
52
53
# File 'lib/http/accept/media_types.rb', line 45

def freeze
	@media_types.freeze
	@media_types.each{|key,value| value.freeze}
	
	@all.freeze
	@all.each(&:freeze)
	
	super
end