Permalink
Browse files

Add a Bailador::App class

It is not really necessary as for now, but it certainly will be later,
and it does make some things easier
  • Loading branch information...
tadzik committed Apr 7, 2012
1 parent 6eb2402 commit 774bd83b00d95dc61e3012bedb9c4dff466ed743
Showing with 45 additions and 16 deletions.
  1. +12 −16 lib/Bailador.pm
  2. +33 −0 lib/Bailador/App.pm
View
@@ -1,13 +1,11 @@
module Bailador;
+use Bailador::App;
use Bailador::Request;
use Bailador::Response;
use Ratel;
use HTTP::Easy::PSGI;
-my %routes;
-%routes<GET> = [];
-%routes<POST> = [];
-
+my $current-app = Bailador::App.current;
my $current-request = Bailador::Request.new;
my $current-response = Bailador::Response.new;
my $template-engine = Ratel.new;
@@ -34,13 +32,13 @@ multi parse_route($route) {
sub get(Pair $x) is export {
my $p = parse_route($x.key) => $x.value;
- %routes<GET>.push: $p;
+ $current-app.add_route: 'GET', $p;
return $x;
}
sub post(Pair $x) is export {
my $p = parse_route($x.key) => $x.value;
- %routes<POST>.push: $p;
+ $current-app.add_route: 'POST', $p;
return $x;
}
@@ -67,16 +65,14 @@ sub dispatch($env) {
$current-response.content = 'Not found';
$current-response.headers<Content-Type> = 'text/html';
- for %routes{$env<REQUEST_METHOD>}.list -> $r {
- next unless $r;
- if $env<REQUEST_URI> ~~ $r.key {
- $current-response.code = 200;
- if $/ {
- unless $/[0] { $/ = $/<_capture> }
- $current-response.content = $r.value.(|$/.list);
- } else {
- $current-response.content = $r.value.();
- }
+ my $r = $current-app.find_route($env);
+ if $r {
+ $current-response.code = 200;
+ if $/ {
+ unless $/[0] { $/ = $/<_capture> }
+ $current-response.content = $r.value.(|$/.list);
+ } else {
+ $current-response.content = $r.value.();
}
}
return $current-response.psgi;
View
@@ -0,0 +1,33 @@
+use Bailador::Request;
+
+class Bailador::App {
+ has %.routes = { GET => [], 'POST' => [] };
+
+ my $current = Bailador::App.new;
+
+ method set-current(Bailador::App $app) { $current = $app }
+ method current { $current }
+
+ multi method find_route(Bailador::Request $req) {
+ self._find_route: $req.method, $req.request_uri
+ }
+
+ # a simplier version to avoid creation of short-living objects
+ multi method find_route($env) {
+ self._find_route: $env<REQUEST_METHOD>, $env<REQUEST_URI>
+ }
+
+ method _find_route($meth, $uri) {
+ for %.routes{$meth}.list -> $r {
+ next unless $r;
+ if $uri ~~ $r.key {
+ return $r;
+ }
+ }
+ return;
+ }
+
+ method add_route($meth, Pair $route) {
+ %.routes{$meth}.push: $route;
+ }
+}

0 comments on commit 774bd83

Please sign in to comment.