Class: Rack::Request::AcceptableMediaTypes

Inherits:
Array
  • Object
show all
Defined in:
lib/rack/acceptable.rb

Defined Under Namespace

Classes: MediaType

Instance Method Summary collapse

Constructor Details

#initialize(*media_types) ⇒ AcceptableMediaTypes

– NOTE Reason for special handling of nil accept header:

“If no Accept header field is present, then it is assumed that the client accepts all media types.”



42
43
44
45
46
47
48
49
50
51
# File 'lib/rack/acceptable.rb', line 42

def initialize(*media_types)
  media_types = media_types.flatten
  if media_types.empty?
    replace(['*/*'])
  elsif media_types.size == 1
    replace(media_types.first.split(','))
  else
    replace(media_types)
  end
end

Instance Method Details

#first_acceptable(*types) ⇒ Object

Pick the first acceptable of a list of media types. This is useful for serving html to broken browsers (>_> Safari) that provide a wrong Accept header.

Example:

accept = AcceptableMediaTypes.new("application/xml;q=1.0,text/html;q=0.1")
accept.first_acceptable('text/html,application/xml')
#=> 'text/html'


73
74
75
76
# File 'lib/rack/acceptable.rb', line 73

def first_acceptable(*types)
  types = self.class.new(*types)
  types.detect { |type| include?(type) }
end

#preference_of(*types) ⇒ Object

The prefered type out of list of possible media types



79
80
81
82
# File 'lib/rack/acceptable.rb', line 79

def preference_of(*types)
  types = self.class.new(*types)
  detect { |acceptable_type| types.include?(acceptable_type) }
end

#prioritize(*types) ⇒ Object

Prioritize a list of media types in order of client preference



58
59
60
61
# File 'lib/rack/acceptable.rb', line 58

def prioritize(*types)
  types = self.class.new(*types)
  select { |acceptable_type| types.include?(acceptable_type) }
end

#replace(media_types = []) ⇒ Object



53
54
55
# File 'lib/rack/acceptable.rb', line 53

def replace(media_types = [])
  super(order(media_types))
end