Skip to content

Commit

Permalink
using the target attribute to attach a dispatcher
Browse files Browse the repository at this point in the history
  • Loading branch information
Stevan Little committed Mar 16, 2010
1 parent 2dfcc9a commit bab8505
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions path-router.psgi
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -7,12 +7,21 @@ use MyApp::Hello;
use Path::Router; use Path::Router;
use Moose::Util::TypeConstraints; use Moose::Util::TypeConstraints;


sub dispatch {
my ($r, $mapping) = @_;
my $controller = 'MyApp::' . $mapping->{controller};
my $action = $controller->can(lc($r->method) . '_' . $mapping->{action})
or return $r->new_response(405);
$controller->$action($r, $mapping);
}

my $router = Path::Router->new; my $router = Path::Router->new;
$router->add_route('' => ( $router->add_route('' => (
defaults => { defaults => {
controller => 'Hello', controller => 'Hello',
action => 'index', action => 'index',
}, },
target => \&dispatch
)); ));


$router->add_route('blog/:year/:month' => ( $router->add_route('blog/:year/:month' => (
Expand All @@ -23,25 +32,23 @@ $router->add_route('blog/:year/:month' => (
validations => { validations => {
year => subtype( as 'Int' => where { $_ > 0 } ), year => subtype( as 'Int' => where { $_ > 0 } ),
month => subtype( as 'Int' => where { $_ >= 1 && $_ <= 12 } ), month => subtype( as 'Int' => where { $_ >= 1 && $_ <= 12 } ),
} },
target => \&dispatch
)); ));


$router->add_route('comment', => ( $router->add_route('comment', => (
defaults => { defaults => {
controller => 'Blog', controller => 'Blog',
action => 'comment', action => 'comment',
}, },
target => \&dispatch
)); ));


sub { sub {
my $req = Plack::Request->new(shift); my $req = Plack::Request->new(shift);
my $match = $router->match($req->path_info) my $match = $router->match($req->path_info)
or return $req->new_response(404)->finalize; or return $req->new_response(404)->finalize;


my $mapping = $match->mapping; my $res = $match->target->($req, $match->mapping);
my $controller = "MyApp::" . $mapping->{controller};
my $action = $controller->can(lc($req->method) . "_" . $mapping->{action})
or return $req->new_response(405)->finalize;
my $res = $controller->$action($req, $mapping);
$res->finalize; $res->finalize;
}; };

0 comments on commit bab8505

Please sign in to comment.