Class: Patchbay::Router

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

Overview

Parses URLs and matches them to handlers.

Defined Under Namespace

Classes: Route

Instance Method Summary (collapse)

Constructor Details

- (Router) initialize



45
46
47
# File 'lib/patchbay.rb', line 45

def initialize
    @routes = []
end

Instance Method Details

- (Object) add(verb, route, handler)

Add a route matching a certain URL pattern and verb.

Parameters:

verb

The HTTP verb (GET, POST etc)

route

The URL template to match. This may contain symbols of the form `:xxxx`; these represent variable parameters to be extracted from the URL when it is matched.



122
123
124
125
126
127
128
129
# File 'lib/patchbay.rb', line 122

def add(verb, route, handler)
    parts = route.gsub(/^\/+/,'').split('/')
    routeObj = Route.new
    routeObj.url_parts = parts
    routeObj.handler = handler
    routeObj.verb = verb
    @routes << routeObj
end

- (Object) match(verb, url)

Find a handler matching an HTTP request.

Parameters:

verb

The HTTP verb (GET, POST etc)

url

The requested URL

Returns:

A 2-element array consisting of the handler followed by a hash of parameters extracted from the URL.



97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/patchbay.rb', line 97

def match(verb, url)
    parts = url.gsub(/^\/+/,'').split('/')

    @routes.each do |route|
        if route.verb == verb
            result = matches?(route, parts)
            if result
                return [ route.handler, result ]
            end
        end
    end

    return [ nil, nil ]
end