Class: Zero::Router

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

Overview

makes it possible to route urls to rack applications

This class can be used to build a small rack application which routes requests to the given application. In the URLs it is also possible to use placeholders which then get assigned as variables to the parameters.

Examples:

of a simple router

router = Zero::Router.new(
  '/' => WelcomeController,
  '/posts' => PostController
)

of a router with variables

router = Zero::Router.new(
  '/foo/:id' => FooController
)

Constant Summary collapse

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

#initialize(routes) ⇒ Router

create a new router instance

Examples:

of a simple router

router = Zero::Router.new(
  '/' => WelcomeController,
  '/posts' => PostController
)

Parameters:

  • routes (Hash)

    a map of URLs to rack compatible applications



34
35
36
37
38
39
40
41
# File 'lib/zero/router.rb', line 34

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

Instance Method Details

#call(env) ⇒ Array

call the router and call the matching application

This method has to be called with a rack compatible environment, then the method will find a matching route and call the application.

Parameters:

  • env (Hash)

    a rack environment

Returns:

  • (Array)

    a rack compatible response



49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/zero/router.rb', line 49

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