Sha256: fd078a5334c8157fc38d29639c3ec9f4ae0eb922b31e0568f727aca037f1b5be

Contents?: true

Size: 1.23 KB

Versions: 20

Compression:

Stored size: 1.23 KB

Contents

# frozen_string_literal: true

module Aserto
  module Sinatra
    module Utils
      class << self
        # Finds the Sinatra route for the given path.
        # If the route is not found, returns nil.
        # If the route is found, returns a hash with the following keys:
        # :path
        # :action
        #
        # Eg:
        # route("/api/v1/users/1") => {
        #   :action => :GET,
        #   :path => "/api/v1/users/:id" }
        def route(request)
          return unless defined? ::Sinatra

          path = request.path_info
          routes = ::Sinatra::Application.routes[request.request_method].map do |route|
            route.flatten.first
          end
          route = routes.find do |r|
            r.match(path)
          end

          return unless route

          substitutions = route.match(path).named_captures
          unless substitutions&.any?
            return {
              path: route.to_s,
              action: request.request_method.to_sym
            }
          end

          substitutions.each_pair do |sub, val|
            path.sub!(val, ":#{sub}")
          end
          {
            path: path,
            action: request.request_method.to_sym
          }
        end
      end
    end
  end
end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
aserto-0.31.3 lib/aserto/sinatra/utils.rb
aserto-0.31.2 lib/aserto/sinatra/utils.rb
aserto-0.31.1 lib/aserto/sinatra/utils.rb
aserto-0.31.0 lib/aserto/sinatra/utils.rb
aserto-0.30.6 lib/aserto/sinatra/utils.rb
aserto-0.30.5 lib/aserto/sinatra/utils.rb
aserto-0.30.4 lib/aserto/sinatra/utils.rb
aserto-0.30.1 lib/aserto/sinatra/utils.rb
aserto-0.30.0 lib/aserto/sinatra/utils.rb
aserto-0.20.6 lib/aserto/sinatra/utils.rb
aserto-0.20.5 lib/aserto/sinatra/utils.rb
aserto-0.20.4 lib/aserto/sinatra/utils.rb
aserto-0.20.3 lib/aserto/sinatra/utils.rb
aserto-0.20.2 lib/aserto/sinatra/utils.rb
aserto-0.0.6 lib/aserto/sinatra/utils.rb
aserto-0.0.5 lib/aserto/sinatra/utils.rb
aserto-0.0.4 lib/aserto/sinatra/utils.rb
aserto-0.0.3 lib/aserto/sinatra/utils.rb
aserto-0.0.2 lib/aserto/sinatra/utils.rb
aserto-0.0.1 lib/aserto/sinatra/utils.rb