Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kelp: allow multiple instances of an app #62

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions lib/Kelp.pm
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ attr -loaded_modules => sub { {} };
attr req => undef;
attr res => undef;

attr -registered_methods => sub { {} };

# Initialization
sub new {
my $self = shift->SUPER::new(@_);
Expand Down Expand Up @@ -80,6 +82,30 @@ sub _clone {
return bless { %$self }, $subclass;
}

# Check our instance-registered methods for can()
sub can {
my ($self, $name) = @_;
if (ref $self) {
my $method = $self->registered_methods->{$name};
return $method if defined $method;
}
return $self->SUPER::can($name);
}

# Check our instance-registered methods for implementations
our $AUTOLOAD;
sub AUTOLOAD {
my $self = shift;

my $name = $AUTOLOAD =~ s/.*:://r;
return if $name eq "DESTROY";

my $method = $self->can($name);
return $self->$method(@_) if $method;
die sprintf('Can\'t locate object method "%s" via package "%s"',
$name, ref $self);
}

sub load_module {
my ( $self, $name, %args ) = @_;

Expand Down
9 changes: 3 additions & 6 deletions lib/Kelp/Module.pm
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,17 @@ sub register {
no strict 'refs';
no warnings 'redefine';

my $app = ref $self->app;
my $glob = "${app}::$name";

# Manually check if the glob is being redefined
if ( !$ENV{KELP_REDEFINE} && $self->app->can($name) ) {
croak "Redefining of $glob not allowed";
croak "Redefining of $name not allowed";
}

if ( ref $item eq 'CODE' ) {
*{$glob} = $item;
$self->app->registered_methods->{$name} = $item;
}
else {
$self->app->{$name} = $item;
*{$glob} = sub { $_[0]->{$name} }
$self->app->registered_methods->{$name} = sub { $_[0]->{$name} };
}
}
}
Expand Down
5 changes: 2 additions & 3 deletions t/module_config.t
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,10 @@ use Plack::Util;
use FindBin '$Bin';
use Test::More;
use Test::Exception;
use Kelp;

# Basic
my $app = Plack::Util::inline_object(
mode => sub { "test" }
);
my $app = Kelp->new( mode => 'test' );
my $c = Kelp::Module::Config->new( app => $app );
isa_ok $c, 'Kelp::Module::Config';

Expand Down