Sha256: 49a367f6a9522d450341688cfcd01a2e06e2ab393cba642a24787458296974b1

Contents?: true

Size: 1.42 KB

Versions: 1

Compression:

Stored size: 1.42 KB

Contents

require 'grape/middleware/base'

module Grape
  module Middleware
    module Versioner
      # 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'
      #
      class Path < Base
        def default_options
          {
            pattern: /.*/i
          }
        end

        def before
          path = env[Grape::Http::Headers::PATH_INFO].dup

          if prefix && path.index(prefix).zero?
            path.sub!(prefix, '')
            path = Grape::Router.normalize_path(path)
          end

          pieces = path.split('/')
          potential_version = pieces[1]
          return unless potential_version =~ 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

        private

        def prefix
          Grape::Router.normalize_path(options[:prefix].to_s) if options[:prefix]
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
grape-0.19.0 lib/grape/middleware/versioner/path.rb