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/greedy_route.rb,
lib/grape/router/attribute_translator.rb

Defined Under Namespace

Classes: AttributeTranslator, GreedyRoute, Pattern, Route

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRouter

Returns a new instance of Router.



23
24
25
26
27
28
# File 'lib/grape/router.rb', line 23

def initialize
  @neutral_map = []
  @neutral_regexes = []
  @map = Hash.new { |hash, key| hash[key] = [] }
  @optimized_map = Hash.new { |hash, key| hash[key] = // }
end

Instance Attribute Details

#compiledObject (readonly)

Returns the value of attribute compiled.



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

def compiled
  @compiled
end

#mapObject (readonly)

Returns the value of attribute map.



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

def map
  @map
end

Class Method Details

.normalize_path(path) ⇒ Object



11
12
13
14
15
16
17
# File 'lib/grape/router.rb', line 11

def self.normalize_path(path)
  path = +"/#{path}"
  path.squeeze!('/')
  path.sub!(%r{/+\Z}, '')
  path = '/' if path == ''
  path
end

.supported_methodsObject



19
20
21
# File 'lib/grape/router.rb', line 19

def self.supported_methods
  @supported_methods ||= Grape::Http::Headers::SUPPORTED_METHODS + ['*']
end

Instance Method Details

#append(route) ⇒ Object



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

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

#associate_routes(pattern, **options) ⇒ Object



50
51
52
53
# File 'lib/grape/router.rb', line 50

def associate_routes(pattern, **options)
  @neutral_regexes << Regexp.new("(?<_#{@neutral_map.length}>)#{pattern.to_regexp}")
  @neutral_map << Grape::Router::GreedyRoute.new(pattern: pattern, index: @neutral_map.length, **options)
end

#call(env) ⇒ Object



55
56
57
58
59
60
# File 'lib/grape/router.rb', line 55

def call(env)
  with_optimization do
    response, route = identity(env)
    response || rotation(env, route)
  end
end

#compile!Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/grape/router.rb', line 30

def compile!
  return if compiled

  @union = Regexp.union(@neutral_regexes)
  @neutral_regexes = nil
  self.class.supported_methods.each do |method|
    routes = map[method]
    @optimized_map[method] = routes.map.with_index do |route, index|
      route.index = index
      Regexp.new("(?<_#{index}>#{route.pattern.to_regexp})")
    end
    @optimized_map[method] = Regexp.union(@optimized_map[method])
  end
  @compiled = true
end

#recognize_path(input) ⇒ Object



62
63
64
65
66
67
# File 'lib/grape/router.rb', line 62

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

  any.endpoint
end