Class: Whoosh::Router

Inherits:
Object
  • Object
show all
Defined in:
lib/whoosh/router.rb

Defined Under Namespace

Classes: TrieNode

Constant Summary collapse

EMPTY_PARAMS =
{}.freeze

Instance Method Summary collapse

Constructor Details

#initializeRouter

Returns a new instance of Router.



18
19
20
21
22
23
# File 'lib/whoosh/router.rb', line 18

def initialize
  @root = TrieNode.new
  @routes = []
  @frozen = false
  @static_cache = nil
end

Instance Method Details

#add(method, path, handler, **metadata) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/whoosh/router.rb', line 25

def add(method, path, handler, **)
  raise "Router is frozen — cannot add routes after boot" if @frozen

  node = @root
  segments = split_path(path)

  segments.each do |segment|
    if segment.start_with?(":")
      child = node.children[:_param] ||= TrieNode.new
      child.is_param = true
      child.param_name = segment[1..].to_sym
      node = child
    else
      node = node.children[segment] ||= TrieNode.new
    end
  end

  node.handlers[method] = { handler: handler, metadata:  }
  @routes << { method: method, path: path, handler: handler, metadata:  }
end

#freeze!Object



86
87
88
89
# File 'lib/whoosh/router.rb', line 86

def freeze!
  @frozen = true
  build_static_cache
end

#match(method, path) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/whoosh/router.rb', line 46

def match(method, path)
  # Fast path: static route cache (O(1))
  if @static_cache
    cached = @static_cache["#{method}:#{path}"]
    if cached
      return { handler: cached[:handler], params: EMPTY_PARAMS, metadata: cached[:metadata] }
    end
  end

  # Slow path: trie walk for param routes
  # Trailing slash (e.g. "/health/") is treated as a distinct path from "/health"
  return nil if path.end_with?("/") && path != "/"

  node = @root
  params = {}
  segments = split_path(path)

  segments.each do |segment|
    if node.children[segment]
      node = node.children[segment]
    elsif node.children[:_param]
      node = node.children[:_param]
      params[node.param_name] = segment
    else
      return nil
    end
  end

  entry = node.handlers[method]
  return nil unless entry

  { handler: entry[:handler], params: params.empty? ? EMPTY_PARAMS : params, metadata: entry[:metadata] }
end

#routesObject



80
81
82
83
84
# File 'lib/whoosh/router.rb', line 80

def routes
  @routes.map do |route|
    { method: route[:method], path: route[:path], metadata: route[:metadata] }
  end
end