Class: Grape::Middleware::Versioner::Header

Inherits:
Base
  • Object
show all
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.a-cool-resource-v1+json

The following rack env variables are set:

env['api.type'] => 'application' env['api.subtype'] => 'vnd.mycompany.a-cool-resource-v1+json' env['api.vendor] => 'mycompany.a-cool-resource' env['api.version] => 'v1' env['api.format] => 'json'

If version does not match this route, then a 406 is raised with X-Cascade header to alert Grape::Router to attempt the next matched route.

Constant Summary collapse

VENDOR_VERSION_HEADER_REGEX =
/\Avnd\.([a-z0-9.\-_!#{Regexp.last_match(0)}\^]+?)(?:-([a-z0-9*.]+))?(?:\+([a-z0-9*\-.]+))?\z/.freeze
HAS_VENDOR_REGEX =
/\Avnd\.[a-z0-9.\-_!#{Regexp.last_match(0)}\^]+/.freeze
HAS_VERSION_REGEX =
/\Avnd\.([a-z0-9.\-_!#{Regexp.last_match(0)}\^]+?)(?:-([a-z0-9*.]+))+/.freeze

Constants inherited from Base

Base::TEXT_HTML

Instance Attribute Summary

Attributes inherited from Base

#app, #env, #options

Instance Method Summary collapse

Methods inherited from Base

#after, #call, #call!, #content_type, #content_type_for, #content_types, #default_options, #initialize, #mime_types, #response

Methods included from Helpers

#context

Constructor Details

This class inherits a constructor from Grape::Middleware::Base

Instance Method Details

#beforeObject



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/grape/middleware/versioner/header.rb', line 34

def before
  strict_header_checks if strict?

  if media_type || env[Grape::Env::GRAPE_ALLOWED_METHODS]
    media_type_header_handler
  elsif headers_contain_wrong_vendor?
    fail_with_invalid_accept_header!('API vendor not found.')
  elsif headers_contain_wrong_version?
    fail_with_invalid_version_header!('API version not found.')
  end
end