Skip to content

Commit

Permalink
instanciate controller classes on request
Browse files Browse the repository at this point in the history
this commit adds a new feature
  • Loading branch information
zurborg committed Sep 1, 2014
1 parent 9f9141b commit 81c5b34
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 4 deletions.
29 changes: 25 additions & 4 deletions lib/Dancer/Plugin/Dispatcher.pm
Expand Up @@ -132,6 +132,8 @@ use Class::Load qw/load_class/;

# automation ... sorta

our $classes;

sub dispatcher {
return unless config->{plugins};

Expand Down Expand Up @@ -173,10 +175,15 @@ sub dispatcher {

# build the return code (+chain if specified)
$code = sub {
load_class($class);
debug lc "dispatching $class -> $action";
croak "action $action not found in class $class" unless $class->can($action);
$class->$action(@_) if $class && $action;
debug "dispatching $class -> $action";
if (exists $classes->{$class}) {
croak "action $action not found in class $class" unless $classes->{$class}->can($action);
$classes->{$class}->$action(@_);
} else {
load_class($class);
croak "action $action not found in class $class" unless $class->can($action);
$class->$action(@_) if $class && $action;
}
};

return $code;
Expand Down Expand Up @@ -229,6 +236,20 @@ sub auto_dispatcher {

register dispatch => \&dispatcher;

register boot_classes => sub {
return unless config->{plugins};

our $cfg = config->{plugins}->{Dispatcher};

my %def = (%{$cfg->{boot}}, @_);

foreach my $class (keys %def) {
load_class($class);
debug "instanciate class $class";
$classes->{$class} = $class->new(@{$def{$class}});
}
};

register_plugin;
auto_dispatcher;

Expand Down
18 changes: 18 additions & 0 deletions t/04-obj.t
@@ -0,0 +1,18 @@
#!perl

use Test::More tests => 3, import => ['!pass'];
use Dancer::Test;

BEGIN {
use FindBin;
use lib "$FindBin::Bin/lib";
use_ok 'MyAppObj';
}

response_content_is [GET => '/incr'],
'1', '/incr returned 1';

response_content_is [GET => '/incr'],
'2', '/incr returned 2';

1;
31 changes: 31 additions & 0 deletions t/lib/MyAppObj.pm
@@ -0,0 +1,31 @@
package MyAppObj;

BEGIN {
use Dancer ':syntax';
set plugins => {
Dispatcher => {
base => 'MyAppObj',
boot => {
MyAppObj => [ { i => 0 } ]
}
}
};
}

use Dancer::Plugin::Dispatcher;

sub new {
my ($class, $config) = @_;
return bless $config => ref $class || $class;
}

sub incr {
my $self = shift;
++$self->{i};
}

boot_classes;

get '/incr' => dispatch '#incr';

1;

0 comments on commit 81c5b34

Please sign in to comment.