Class: Grape::Middleware::Versioner::AcceptVersionHeader

Inherits:
Base
  • Object
show all
Defined in:
lib/grape/middleware/versioner/accept_version_header.rb

Overview

This middleware sets various version related rack environment variables based on the HTTP Accept-Version header

Example: For request header

Accept-Version: v1

The following rack env variables are set:

env['api.version']  => 'v1'

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

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 DSL::Headers

#header

Methods included from Helpers

#context

Constructor Details

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

Instance Method Details

#beforeObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/grape/middleware/versioner/accept_version_header.rb', line 22

def before
  potential_version = (env[Grape::Http::Headers::HTTP_ACCEPT_VERSION] || '').strip

  if strict?
    # If no Accept-Version header:
    if potential_version.empty?
      throw :error, status: 406, headers: error_headers, message: 'Accept-Version header must be set.'
    end
  end

  return if potential_version.empty?

  # If the requested version is not supported:
  throw :error, status: 406, headers: error_headers, message: 'The requested version is not supported.' unless versions.any? { |v| v.to_s == potential_version }

  env[Grape::Env::API_VERSION] = potential_version
end