Class: Zero::Router

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

Constant Summary

VARIABLE_MATCH =

match for variables in routes

%r{:(\w+)[^/]?}
VARIABLE_REGEX =

the replacement string to make it an regex

'(?<\1>.+?)'

Instance Method Summary (collapse)

Constructor Details

- (Router) initialize(routes)

A new instance of Router



8
9
10
11
12
13
14
15
# File 'lib/zero/router.rb', line 8

def initialize(routes)
  @routes = {}
  routes.each do |route, target|
    @routes[
      Regexp.new(
        route.gsub(VARIABLE_MATCH, VARIABLE_REGEX) + '$')] = target
  end
end

Instance Method Details

- (Object) call(env)



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/zero/router.rb', line 17

def call(env)
  request = Zero::Request.create(env)
  @routes.each do |route, target|
    match = route.match(request.path)
    if match
      match.names.each_index do |i|
        request.update_param(match.names[i], match.captures[i])
      end
      return target.call(request.env)
    end
  end
  [404, {'Content-Type' => 'text/html'}, ['Not found!']]
end