Class: Tennpipes::PathRouter::Compiler

Inherits:
Object
  • Object
show all
Defined in:
lib/tennpipes-base/path_router/compiler.rb

Overview

High performance engine for finding all routes which are matched with pattern

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(routes) ⇒ Compiler

Constructs an instance of Tennpipes::PathRouter::Compiler



13
14
15
# File 'lib/tennpipes-base/path_router/compiler.rb', line 13

def initialize(routes)
  @routes = routes
end

Instance Attribute Details

#regexpsObject (readonly)

All regexps generated by recursive compiler



8
9
10
# File 'lib/tennpipes-base/path_router/compiler.rb', line 8

def regexps
  @regexps
end

Instance Method Details

#call_by_request(request) ⇒ Object

Calls routes by using request.



50
51
52
53
54
55
56
57
58
59
# File 'lib/tennpipes-base/path_router/compiler.rb', line 50

def call_by_request(request)
  rotation do |offset|
    pattern  = encode_default_external(request.path_info)
    if route = match?(offset, pattern)
      params = route.params_for(pattern, request.params)
      yield(route, params) if route.verb == request.request_method
      route
    end
  end
end

#compile!Object

Compiles all routes into regexps.



20
21
22
23
24
25
26
27
28
# File 'lib/tennpipes-base/path_router/compiler.rb', line 20

def compile!
  return if compiled?
  @regexps = @routes.map.with_index do |route, index|
    route.index = index
    /(?<_#{index}>#{route.matcher.to_regexp})/
  end
  @regexps = recursive_compile(@regexps)
  @compiled = true
end

#compiled?Boolean

Returns true if all routes has been compiled.

Returns:

  • (Boolean)


33
34
35
# File 'lib/tennpipes-base/path_router/compiler.rb', line 33

def compiled?
  !!@compiled
end

#find_by(request_or_env) ⇒ Object

Finds routes by using request or env.



40
41
42
43
44
45
# File 'lib/tennpipes-base/path_router/compiler.rb', line 40

def find_by(request_or_env)
  request = request_or_env.is_a?(Hash) ? Sinatra::Request.new(request_or_env) : request_or_env
  pattern = encode_default_external(request.path_info)
  verb    = request.request_method
  rotation { |offset| match?(offset, pattern) }.select { |route| route.verb == verb }
end

#find_by_pattern(pattern) ⇒ Object

Finds routes by using PATH_INFO.



64
65
66
67
# File 'lib/tennpipes-base/path_router/compiler.rb', line 64

def find_by_pattern(pattern)
  pattern = pattern.encode(Encoding.default_external)
  rotation { |offset| match?(offset, pattern) }
end