Class: Grape::Router

Inherits:
Object
  • Object
show all
Defined in:
lib/grape/router.rb,
lib/grape/router/route.rb,
lib/grape/router/pattern.rb,
lib/grape/router/base_route.rb,
lib/grape/router/greedy_route.rb,
lib/grape/router/mustermann_pattern.rb

Defined Under Namespace

Classes: BaseRoute, GreedyRoute, MustermannPattern, Pattern, Route

Constant Summary collapse

DEFAULT_RESPONSE_HEADERS =
Grape::Util::Header.new.merge('X-Cascade' => 'pass').freeze
DEFAULT_RESPONSE_BODY =
['404 Not Found'].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRouter

Returns a new instance of Router.



13
14
15
16
17
18
19
20
21
# File 'lib/grape/router.rb', line 13

def initialize
  @neutral_map = []
  @neutral_regexes = []
  # Plain hashes with no auto-vivifying default: a lookup for an HTTP method
  # that has no routes must not insert a key. `compile!` freezes both maps,
  # so request-time reads never mutate shared state (see #match? / #rotation).
  @map = {}
  @optimized_map = {}
end

Class Method Details

.normalize_path(path) ⇒ Object

Deprecated.


6
7
8
9
10
11
# File 'lib/grape/router.rb', line 6

def self.normalize_path(path)
  Grape.deprecator.warn(
    '`Grape::Router.normalize_path` is deprecated. Use `Grape::Util::PathNormalizer.call` instead.'
  )
  Grape::Util::PathNormalizer.call(path)
end

Instance Method Details

#append(route) ⇒ Object



40
41
42
# File 'lib/grape/router.rb', line 40

def append(route)
  (@map[route.request_method] ||= []) << route
end

#associate_routes(greedy_route) ⇒ Object



44
45
46
47
# File 'lib/grape/router.rb', line 44

def associate_routes(greedy_route)
  @neutral_regexes << greedy_route.to_regexp(@neutral_map.length)
  @neutral_map << greedy_route
end

#call(env) ⇒ Object



49
50
51
52
53
54
55
56
# File 'lib/grape/router.rb', line 49

def call(env)
  with_optimization do
    input = Grape::Util::PathNormalizer.call(env[Rack::PATH_INFO])
    method = env[Rack::REQUEST_METHOD]
    response, route = identity(input, method, env)
    response || rotation(input, method, env, route)
  end
end

#compile!Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/grape/router.rb', line 23

def compile!
  return if @compiled

  @union = Regexp.union(@neutral_regexes)
  @neutral_regexes = nil
  (Grape::HTTP_SUPPORTED_METHODS + ['*']).each do |method|
    next unless @map.key?(method)

    routes = @map[method]
    optimized_map = routes.map.with_index { |route, index| route.to_regexp(index) }
    @optimized_map[method] = Regexp.union(optimized_map)
  end
  @map.freeze
  @optimized_map.freeze
  @compiled = true
end

#recognize_path(input) ⇒ Object



58
59
60
61
62
63
# File 'lib/grape/router.rb', line 58

def recognize_path(input)
  any = with_optimization { greedy_match?(input) }
  return if any == default_response

  any.endpoint
end