Class: Grape::Middleware::Versioner::Path
- 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
Instance Attribute Summary
Attributes inherited from Base
#available_media_types, #error_headers, #versions
Attributes inherited from Base
Instance Method Summary collapse
- #before ⇒ Object
-
#initialize(app, **options) ⇒ Path
constructor
A new instance of Path.
Methods inherited from Base
inherited, #potential_version_match?, #version_not_found!
Methods included from PrecomputedContentTypes
#content_type, #content_type_for, #content_types, #mime_types
Methods inherited from Base
#after, #call, #call!, #context, #query_params, #rack_request, #response
Methods included from DSL::Headers
Constructor Details
#initialize(app, **options) ⇒ Path
Returns a new instance of Path.
20 21 22 23 |
# File 'lib/grape/middleware/versioner/path.rb', line 20 def initialize(app, **) super @prefixes = [mount_path, Grape::Util::PathNormalizer.call(prefix)].select { |p| p.present? && p != '/' }.freeze end |
Instance Method Details
#before ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/grape/middleware/versioner/path.rb', line 25 def before routed = routed_version return env[Grape::Env::API_VERSION] = routed if routed path_info = env[Grape::Env::GRAPE_NORMALIZED_PATH] || Grape::Util::PathNormalizer.call(env[Rack::PATH_INFO]) return if path_info == '/' # `each` rather than `reduce`: Array does not override Enumerable's, # so the generic accumulator path costs more than the work it drives # on a list that holds at most a mount path and a prefix — and most # often nothing at all. @prefixes.each { |prefix| path_info = path_info.delete_prefix(prefix) if path_info.start_with?(prefix) } slash_position = path_info.index('/', 1) # omit the first one return version_from_first_segment(path_info, slash_position) if slash_position version_from_only_segment(path_info) end |