Module: Tina4::Router

Defined in:
lib/tina4/router.rb

Defined Under Namespace

Classes: GroupContext

Class Method Summary collapse

Class Method Details

.add_route(method, path, handler, auth_handler: nil, swagger_meta: {}) ⇒ Object



94
95
96
97
98
99
100
# File 'lib/tina4/router.rb', line 94

def add_route(method, path, handler, auth_handler: nil, swagger_meta: {})
  route = Route.new(method, path, handler, auth_handler: auth_handler, swagger_meta: swagger_meta)
  routes << route
  method_index[route.method] << route
  Tina4::Debug.debug("Route registered: #{method.upcase} #{path}")
  route
end

.clear!Object



118
119
120
121
# File 'lib/tina4/router.rb', line 118

def clear!
  @routes = []
  @method_index = Hash.new { |h, k| h[k] = [] }
end

.find_route(path, method) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/tina4/router.rb', line 102

def find_route(path, method)
  normalized_method = method.upcase
  # Normalize path once (not per-route)
  normalized_path = path.gsub("\\", "/")
  normalized_path = "/#{normalized_path}" unless normalized_path.start_with?("/")
  normalized_path = normalized_path.chomp("/") unless normalized_path == "/"

  # Only scan routes matching this HTTP method
  candidates = method_index[normalized_method]
  candidates.each do |route|
    params = route.match_path(normalized_path)
    return [route, params] if params
  end
  nil
end

.group(prefix, auth_handler: nil, &block) ⇒ Object



123
124
125
# File 'lib/tina4/router.rb', line 123

def group(prefix, auth_handler: nil, &block)
  GroupContext.new(prefix, auth_handler).instance_eval(&block)
end

.method_indexObject

Routes indexed by HTTP method for O(1) method lookup



90
91
92
# File 'lib/tina4/router.rb', line 90

def method_index
  @method_index ||= Hash.new { |h, k| h[k] = [] }
end

.routesObject



85
86
87
# File 'lib/tina4/router.rb', line 85

def routes
  @routes ||= []
end