Class: Restfulness::Headers::Accept
- Inherits:
-
Object
- Object
- Restfulness::Headers::Accept
- Defined in:
- lib/restfulness/headers/accept.rb
Overview
The Accept header handler provides an array of Media Types that the client is willing to accept.
Based on a simplified RFC2616 implementation, each media type is stored and ordered.
Restfulness does not currently deal with the special 'q' paremeter defined in the standard as quality is not something APIs normally need to handle.
Aside from media type detection, a useful feature of the accept header is to provide the desired version of content to provide in the response. This class offers a helper method that will attempt to determine the version.
Given the HTTP header:
Accept: application/com.example.api+json;version=1
The resource instace has access to the version via:
request.accept.version == "1"
Instance Attribute Summary collapse
-
#media_types ⇒ Object
The -ordered- array of media types provided in the headers.
Instance Method Summary collapse
-
#initialize(str = "") ⇒ Accept
constructor
A new instance of Accept.
- #json? ⇒ Boolean
- #parse(str) ⇒ Object
- #text? ⇒ Boolean
-
#version ⇒ Object
Request the version, always assumes that the first media type is the most relevant.
- #xml? ⇒ Boolean
Constructor Details
#initialize(str = "") ⇒ Accept
Returns a new instance of Accept.
30 31 32 33 |
# File 'lib/restfulness/headers/accept.rb', line 30 def initialize(str = "") self.media_types = [] parse(str) unless str.empty? end |
Instance Attribute Details
#media_types ⇒ Object
The -ordered- array of media types provided in the headers
28 29 30 |
# File 'lib/restfulness/headers/accept.rb', line 28 def media_types @media_types end |
Instance Method Details
#json? ⇒ Boolean
49 50 51 52 53 54 |
# File 'lib/restfulness/headers/accept.rb', line 49 def json? media_types.each do |mt| return true if mt.json? end false end |
#parse(str) ⇒ Object
35 36 37 38 39 40 41 42 |
# File 'lib/restfulness/headers/accept.rb', line 35 def parse(str) types = str.split(',').map{|t| t.strip} # Attempt to crudely determine order based on length, and store types.sort{|a,b| b.length <=> a.length}.each do |t| media_types << MediaType.new(t) end end |
#text? ⇒ Boolean
63 64 65 66 67 68 |
# File 'lib/restfulness/headers/accept.rb', line 63 def text? media_types.each do |mt| return true if mt.text? end false end |
#version ⇒ Object
Request the version, always assumes that the first media type is the most relevant
45 46 47 |
# File 'lib/restfulness/headers/accept.rb', line 45 def version media_types.first.version end |
#xml? ⇒ Boolean
56 57 58 59 60 61 |
# File 'lib/restfulness/headers/accept.rb', line 56 def xml? media_types.each do |mt| return true if mt.xml? end false end |