Class: NuHttp::Router

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

Defined Under Namespace

Classes: Route

Constant Summary collapse

NOT_FOUND_ROUTE =
Route.new(
  method: :internal,
  pattern: nil,
  handler: Ractor.shareable_proc do |c|
    c.res.status = 404
    c.res.body = "Not Found\n"
  end
)

Instance Method Summary collapse

Constructor Details

#initializeRouter

Returns a new instance of Router.



17
18
19
# File 'lib/nuhttp/router.rb', line 17

def initialize
  @routes = []
end

Instance Method Details

#register_route(method, pattern, &block) ⇒ Object



26
27
28
# File 'lib/nuhttp/router.rb', line 26

def register_route(method, pattern, &block)
 @routes << Route.new(method:, pattern:, handler: block)
end

#resolve(req) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/nuhttp/router.rb', line 31

def resolve(req)
  @routes.each do |route|
    # Turn the user supplied pattern into a regexp that captures named params.
    param_names = []
    regexp = /\A#{route.pattern.gsub(/:[^\/]+/) {|segment|
      param_names << segment.delete_prefix(':')
          "([^/]+)"
    }}\z/

    # Test if the request path matches the route pattern
    match = regexp.match(req.path)
    next unless match

    params = {}
    param_names.each.with_index do |name, index|
      params[name.to_sym] = match.captures[index]
    end

    return [route, params]
  end

  # If no route matches, return a fixed 404 response
  [NOT_FOUND_ROUTE, {}]
end

#routesObject



21
22
23
# File 'lib/nuhttp/router.rb', line 21

def routes
  @routes
end