Sha256: 018542a1c5b7f6919ad4fdf2acdc2b902b15a18caef73e3914b8e84a108d322f

Contents?: true

Size: 1.85 KB

Versions: 14

Compression:

Stored size: 1.85 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
          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 =~ 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 mounted_path?(path)
          return false unless mount_path && path.start_with?(mount_path)
          rest = path.slice(mount_path.length..-1)
          rest.start_with?('/') || rest.empty?
        end

        def mount_path
          @mount_path ||= options[:mount_path] && options[:mount_path] != '/' ? options[:mount_path] : ''
        end

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

Version data entries

14 entries across 14 versions & 2 rubygems

Version Path
grape-extra_validators-2.0.0 vendor/bundle/ruby/2.6.0/gems/grape-1.2.5/lib/grape/middleware/versioner/path.rb
grape-extra_validators-1.0.0 vendor/bundle/ruby/2.4.0/gems/grape-1.2.5/lib/grape/middleware/versioner/path.rb
grape-1.2.5 lib/grape/middleware/versioner/path.rb
grape-1.2.4 lib/grape/middleware/versioner/path.rb
grape-1.2.3 lib/grape/middleware/versioner/path.rb
grape-1.2.2 lib/grape/middleware/versioner/path.rb
grape-1.2.1 lib/grape/middleware/versioner/path.rb
grape-1.2.0 lib/grape/middleware/versioner/path.rb
grape-1.1.0 lib/grape/middleware/versioner/path.rb
grape-1.0.3 lib/grape/middleware/versioner/path.rb
grape-1.0.2 lib/grape/middleware/versioner/path.rb
grape-1.0.1 lib/grape/middleware/versioner/path.rb
grape-1.0.0 lib/grape/middleware/versioner/path.rb
grape-0.19.2 lib/grape/middleware/versioner/path.rb