File: Pluggable.pm

package info (click to toggle)
libcatmandu-perl 1.2024-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,552 kB
  • sloc: perl: 17,037; makefile: 24; sh: 1
file content (105 lines) | stat: -rw-r--r-- 1,757 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package Catmandu::Pluggable;

use Catmandu::Sane;

our $VERSION = '1.2024';

use Moo::Role;
use namespace::clean;

sub plugin_namespace {'Catmandu::Plugin'}

sub with_plugins {
    my $class = shift;
    $class = ref $class || $class;
    my @plugins = ref $_[0] eq 'ARRAY' ? @{$_[0]} : @_;
    @plugins = split /,/, join ',', @plugins;
    @plugins || return $class;
    my $ns = $class->plugin_namespace;
    Moo::Role->create_class_with_roles(
        $class,
        map {
            my $pkg = $_;
            if ($pkg !~ s/^\+// && $pkg !~ /^$ns/) {
                $pkg = "${ns}::${pkg}";
            }
            $pkg;
        } @plugins
    );
}

1;

__END__

=pod

=head1 NAME

Catmandu::Pluggable - A role for classes that need plugin capabilities

=head1 SYNOPSIS

    package My::Foo::Bar;

    use Role::Tiny;

    before foo => sub {
        print "Before foo!\n";
    };

    after foo => sub {
        print "After foo!\n";
    };

    sub extra {
        print "I can do extra too\n";
    }

    package My::Foo;

    use Moo;

    with 'Catmandu::Pluggable';

    sub plugin_namespace {
        'My::Foo';
    }

    sub foo {
        print "Foo!\n";
    }

    package main;

    my $x = My::Foo->with_plugins('Bar')->new;

    # prints:
    #  Before foo!
    #  Foo!
    #  After foo!
    $x->foo;

    # prints:
    #  I can do extra too
    $x->extra;

=head1 METHODS

=head2 plugin_namespace 

Returns the namespace where all plugins for your class can be found.

=head2 with_plugins(NAME)

=head2 with_plugins(NAME,NAME,...)

This class method returns a subclass of your class with all provided plugins NAME-s implemented.

=head1 SEE ALSO

L<Catmandu::Bag>,
L<Catmandu::Plugin::Datestamps>,
L<Catmandu::Plugin::Versioning>

=cut