Class: Grape::Middleware::Versioner::Path

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

Overview

This middleware sets various version related rack environment variables based on the uri path and removes the version substring from the uri path. If the version substring does not match any potential initialized versions, a 404 error is thrown.

Example: For a uri path /v1/resource

The following rack env variables are set and path is rewritten to '/resource':

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

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, #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



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/grape/middleware/versioner/path.rb', line 28

def before
  path = env[Grape::Http::Headers::PATH_INFO].dup
  path.sub!(mount_path, '') if mounted_path?(path)

  if prefix && path.index(prefix) == 0 # rubocop:disable all
    path.sub!(prefix, '')
    path = Grape::Router.normalize_path(path)
  end

  pieces = path.split('/')
  potential_version = pieces[1]
  return unless potential_version&.match?(options[:pattern])

  throw :error, status: 404, message: '404 API Version Not Found' if options[:versions] && !options[:versions].find { |v| v.to_s == potential_version }
  env[Grape::Env::API_VERSION] = potential_version
end

#default_optionsObject



22
23
24
25
26
# File 'lib/grape/middleware/versioner/path.rb', line 22

def default_options
  {
    pattern: /.*/i
  }
end