Class: Rack::AcceptMediaTypes

Inherits:
Array
  • Object
show all
Defined in:
lib/sinatra/accept_media_types.rb

Overview

AcceptMediaTypes is intended for wrapping env.

It allows ordering of its values (accepted media types) according to their “quality” (preference level).

This wrapper is typically used to determine the request’s prefered media type (see example below).

Examples
env['HTTP_ACCEPT']  #=> 'application/xml;q=0.8,text/html,text/plain;q=0.9'

types = Rack::AcceptMediaTypes.new(env['HTTP_ACCEPT'])
types               #=> ['text/html', 'text/plain', 'application/xml']
types.prefered      #=>  'text/html'
Notes

For simplicity, media type parameters are striped, as they are seldom used in practice. Users who need them are excepted to parse the Accept header manually.

References

HTTP 1.1 Specs:

Defined Under Namespace

Classes: AcceptMediaType

Instance Method Summary collapse

Constructor Details

#initialize(header) ⇒ AcceptMediaTypes

– 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.”



63
64
65
66
67
68
69
# File 'lib/sinatra/accept_media_types.rb', line 63

def initialize(header)
  if header.nil?
    replace(['*/*'])
  else
    replace(order(header.gsub(/ /, '').split(/,/)))
  end
end

Instance Method Details

#preferedObject

The client’s prefered media type.



72
73
74
# File 'lib/sinatra/accept_media_types.rb', line 72

def prefered
  first
end