Merge: Nitcorn: parameterized uris
authorJean Privat <jean@pryen.org>
Sat, 13 Dec 2014 07:50:37 +0000 (02:50 -0500)
committerJean Privat <jean@pryen.org>
Sat, 13 Dec 2014 07:50:37 +0000 (02:50 -0500)
Introduces parameterized uri handling like `/users/:id`.

## Route matching

Route can match variables expression.

~~~
class DummyAction super Action end
var action = new DummyAction
var route = new Route("/users/:id", action)
assert not route.match("/users")
assert route.match("/users/1234")
assert route.match("/users/") # empty id
~~~

Standard comportement still unchanged.

~~~
route = new Route("/users", action)
assert route.match("/users")
assert route.match("/users/1234")
assert not route.match("/issues/1234")
~~~

## Route priority

Priority depends on the order the routes where added to the `Routes` dispatcher.

~~~
var host = new VirtualHost("")
var routes = new Routes(host)

routes.add new Route("/:a/:b/:c", action)
routes.add new Route("/users/:id", action)
routes.add new Route("/:foo", action)

assert routes["/a/b/c"].path == "/:a/:b/:c"
assert routes["/a/b/c/d"].path == "/:a/:b/:c"
assert routes["/users/1234/foo"].path == "/:a/:b/:c"

assert routes["/users/"].path == "/users/:id"
assert routes["users/"].path == "/users/:id"
assert routes["/users/1234"].path == "/users/:id"

assert routes["/users"].path == "/:foo"
assert routes["/"].path == "/:foo"
assert routes[""].path == "/:foo"
~~~

## Accessing uri parameter from Action

Parameters can be accessed by parsing the uri.

~~~
route = new Route("/users/:id", action)
var params = route.parse_params("/users/1234")
assert params.has_key("id")
assert not params.has_key("foo")
assert params["id"] == "1234"
~~~

Or from the `HttpRequest`

~~~
route = new Route("/users/:id", action)
var req = new HttpRequest
req.uri_params = route.parse_params("/users/1234")
assert req.params == ["id"]
assert req.param("id") == "1234"
assert req.param("foo") == null
~~~

Note that in most cases, all this work is automatically done by the nitcorn engine.
Parameters can then be access through the `HttpRequest` given to `Action::answer`.

@xymus et @R4PaSs ça peut vous intéresser.

Pull-Request: #1006
Reviewed-by: Jean Privat <jean@pryen.org>
Reviewed-by: Lucas Bajolet <r4pass@hotmail.com>
Reviewed-by: Alexis Laferrière <alexis.laf@xymus.net>


Trivial merge