MooX-Object-Pluggable

 view release on metacpan or  search on metacpan

lib/MooX/Object/Pluggable.pm  view on Meta::CPAN

package MooX::Object::Pluggable;
use Moo::Role;
use Modern::Perl;
use Scalar::Util 'refaddr';
require Module::Pluggable::Object;
use namespace::clean;

our $VERSION = '0.0.5'; # VERSION
# ABSTRACT: Moo eXtension to inject plugins to exist objects as a role


sub _apply_roles {
  my ($self, @roles) = @_;
  map {
    my $role = $_;
    Moo::Role->apply_roles_to_object($self, $role) unless $self->does($role)
  } @roles;
  return $self;
}

sub load_plugin { load_plugins(@_) }

sub load_plugins {
  my ($self, @plugin_options) = @_;
  my $pluggable_object = $self->_pluggable_object;
  my @plugins = $pluggable_object->plugins;
  # Provide ability for roles in a real package, with syntax: '+MooX::ConfigFromFile'
  map {
    my $option = $_; $option=~s/^\+//;
    $self->_apply_roles($option);
  } grep { /^\+/ } @plugin_options;
  return $self unless @plugins;
  for my $plugin_option (@plugin_options) {
    if ($plugin_option eq '-all') {
      $self->_apply_roles(@plugins);
    } elsif (ref $plugin_option eq 'ARRAY') {
      $self->load_plugins(@$plugin_option);
    } elsif (ref $plugin_option eq 'Regexp') {
      my @load_plugins = grep { $plugin_option } @plugins;
      return $self unless @load_plugins;
      $self->_apply_roles(@load_plugins);
    } else {
      my @load_plugins = map { $_.'::'.$plugin_option } @{$pluggable_object->{search_path}};
      my %all_plugins = map { $_ => 1 } @plugins;
      my @real_roles = grep { $all_plugins{$_} } @load_plugins;
      return $self unless @real_roles;
      $self->_apply_roles(@real_roles)
    }
  }
  return $self;
}


sub plugins {
  my ($self) = @_;
  $self->_pluggable_object->plugins;
}


sub loaded_plugins {
  my $self = shift;
  grep { $self->does($_) } $self->plugins;
}



( run in 2.731 seconds using v1.01-cache-2.11-cpan-75ffa21a3d4 )