From 3b4c8e20ecc690836ff7f7ea7889bbcd43b3d3e8 Mon Sep 17 00:00:00 2001 From: Jesse Luehrs Date: Wed, 29 May 2013 01:20:26 -0500 Subject: plugin loading --- lib/App/REPL.pm | 48 ++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 38 insertions(+), 10 deletions(-) (limited to 'lib') diff --git a/lib/App/REPL.pm b/lib/App/REPL.pm index f9262fb..6f74385 100644 --- a/lib/App/REPL.pm +++ b/lib/App/REPL.pm @@ -4,14 +4,42 @@ use warnings; use App::REPL::Plugin::Defaults; +use Module::Runtime qw(compose_module_name use_package_optimistically); +use Scalar::Util qw(blessed); + sub new { bless { - plugins => [ + plugins => [], + _default_plugins => [ App::REPL::Plugin::Defaults->new, - ] + ], }, shift; } +sub load_plugin { + my $self = shift; + my ($plugin) = @_; + + if (!blessed($plugin)) { + $plugin = compose_module_name("App::REPL::Plugin", $plugin); + use_package_optimistically($plugin); + die "$plugin is not a valid plugin" + unless $plugin->isa("App::REPL::Plugin"); + $plugin = $plugin->new; + } + + push @{ $self->{plugins} }, $plugin; +} + +sub plugins { + my $self = shift; + + return ( + @{ $self->{plugins} }, + @{ $self->{_default_plugins} }, + ); +} + sub run { my $self = shift; @@ -49,27 +77,27 @@ sub _print { sub _wrapped_plugin { my $self = shift; - my $plugins = ref($_[0]) ? pop : $self->{plugins}; + my @plugins = ref($_[0]) ? @{ shift() } : $self->plugins; my ($method, @args) = @_; - $plugins = [ grep { $_->can($method) } @$plugins ]; + @plugins = grep { $_->can($method) } @plugins; - return @args unless @$plugins; + return @args unless @plugins; - my $plugin = shift @$plugins; - my $next = sub { $self->_wrapped_plugin($plugins, @_) }; + my $plugin = shift @plugins; + my $next = sub { $self->_wrapped_plugin(\@plugins, $method, @_) }; return $plugin->$method($next, @args); } sub _chained_plugin { my $self = shift; - my $plugins = ref($_[0]) ? pop : $self->{plugins}; + my @plugins = ref($_[0]) ? @{ shift() } : $self->plugins; my ($method, @args) = @_; - $plugins = [ grep { $_->can($method) } @$plugins ]; + @plugins = grep { $_->can($method) } @plugins; - for my $plugin (@$plugins) { + for my $plugin (@plugins) { @args = $plugin->$method(@args); } -- cgit v1.2.3-54-g00ecf