Class: Grape::Middleware::Versioner::Header
- Defined in:
- lib/grape/middleware/versioner/header.rb
Overview
This middleware sets various version related rack environment variables based on the HTTP Accept header with the pattern: application/vnd.:vendor-:version+:format
Example: For request header
Accept: application/vnd.mycompany-v1+json
The following rack env variables are set:
env['api.type'] => 'application'
env['api.subtype'] => 'vnd.mycompany-v1+json'
env['api.vendor] => 'mycompany'
env['api.version] => 'v1'
env['api.format] => 'format'
If version does not match this route, then a 406 is throw with X-Cascade header to alert Rack::Mount to attempt the next matched route.
Instance Attribute Summary
Attributes inherited from Base
Instance Method Summary collapse
Methods inherited from Base
#after, #call, #call!, #default_options, #initialize, #request, #response
Constructor Details
This class inherits a constructor from Grape::Middleware::Base
Instance Method Details
#before ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/grape/middleware/versioner/header.rb', line 25 def before accept = env['HTTP_ACCEPT'] || "" if [:version_options] && [:version_options].keys.include?(:strict) && [:version_options][:strict] if (is_accept_header_valid?(accept)) && [:version_options][:using] == :header throw :error, :status => 406, :headers => {'X-Cascade' => 'pass'}, :message => "406 API Version Not Found" end end accept.strip.scan(/^(.+?)\/(.+?)$/) do |type, subtype| env['api.type'] = type env['api.subtype'] = subtype subtype.scan(/vnd\.(.+)?-(.+)?\+(.*)?/) do |vendor, version, format| is_vendored = [:version_options] && [:version_options][:vendor] is_vendored_match = is_vendored ? [:version_options][:vendor] == vendor : true if ([:versions] && ![:versions].include?(version)) || !is_vendored_match throw :error, :status => 406, :headers => {'X-Cascade' => 'pass'}, :message => "406 API Version Not Found" end env['api.version'] = version env['api.vendor'] = vendor env['api.format'] = format # weird that Grape::Middleware::Formatter also does this end end end |