47c325e0a0836fa8d07b1fa9682645d7c4b4e505
[dbsrgits/SQL-Abstract.git] / lib / SQL / Abstract / Role / Plugin.pm
1 package SQL::Abstract::Role::Plugin;
2
3 use Moo::Role;
4
5 has sqla => (
6   is => 'ro', init_arg => undef,
7   handles => [ qw(
8     expand_expr render_aqt join_query_parts
9   ) ],
10 );
11
12 sub cb {
13   my ($self, $method, @args) = @_;
14   return sub {
15     local $self->{sqla} = shift;
16     $self->$method(@args, @_)
17   };
18 }
19
20 sub register {
21   my ($self, @pairs) = @_;
22   my $sqla = $self->sqla;
23   while (my ($method, $cases) = splice(@pairs, 0, 2)) {
24     my @cases = @$cases;
25     while (my ($name, $case) = splice(@cases, 0, 2)) {
26       $sqla->$method($name, $self->cb($case));
27     }
28   }
29   return $self;
30 }
31
32 sub apply_to {
33   my ($self, $sqla) = @_;
34   $self = $self->new unless ref($self);
35   local $self->{sqla} = $sqla;
36   $self->register_extensions($sqla);
37 }
38
39 requires 'register_extensions';
40
41 1;
42
43 __END__
44
45 =head1 NAME
46
47 SQL::Abstract::Role::Plugin - helpful methods for plugin authors
48
49 =head1 METHODS
50
51 =head2 apply_to
52
53 Applies the plugin to an L<SQL::Abstract> object.
54
55 =head2 register_extensions
56
57 Provided by the plugin, registers its extensions to the sqla object.
58
59 =head2 cb
60
61 Creates a callback to call a method on the plugin.
62
63 =head2 register
64
65 Calls methods on the sqla object with arguments wrapped as callbacks.
66
67 =head2 sqla
68
69 Available only during plugin callback executions, contains the currently
70 active L<SQL::Abstract> object.
71
72 =cut