Class: Braintrust::Server::Router

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

Overview

Simple request router that dispatches to handlers based on method + path. Returns 405 for known paths with wrong method, 404 for unknown paths.

Instance Method Summary collapse

Constructor Details

#initializeRouter

Returns a new instance of Router.



10
11
12
# File 'lib/braintrust/server/router.rb', line 10

def initialize
  @routes = {}
end

Instance Method Details

#add(method, path, handler) ⇒ Object



14
15
16
17
# File 'lib/braintrust/server/router.rb', line 14

def add(method, path, handler)
  @routes["#{method} #{path}"] = handler
  self
end

#call(env) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/braintrust/server/router.rb', line 19

def call(env)
  method = env["REQUEST_METHOD"]
  path = env["PATH_INFO"]

  handler = @routes["#{method} #{path}"]
  return handler.call(env) if handler

  # Path exists but wrong method
  if @routes.any? { |key, _| key.end_with?(" #{path}") }
    return [405, {"content-type" => "application/json"},
      [JSON.dump({"error" => "Method not allowed"})]]
  end

  [404, {"content-type" => "application/json"},
    [JSON.dump({"error" => "Not found"})]]
end