Refactored Regex actions
[catagits/Catalyst-Runtime.git] / lib / Catalyst / DispatchType / Regex.pm
1 package Catalyst::DispatchType::Regex;
2
3 use strict;
4 use base qw/Catalyst::DispatchType::Path/;
5 use Text::SimpleTable;
6
7 =head1 NAME
8
9 Catalyst::DispatchType::Regex - Regex DispatchType
10
11 =head1 SYNOPSIS
12
13 See L<Catalyst>.
14
15 =head1 DESCRIPTION
16
17 =head1 METHODS
18
19 =head2 $self->list($c)
20
21 =cut
22
23 sub list {
24     my ( $self, $c ) = @_;
25     my $re = Text::SimpleTable->new( [ 36, 'Regex' ], [ 37, 'Private' ] );
26     for my $regex ( @{ $self->{compiled} } ) {
27         my $action = $regex->{action};
28         $re->row( $regex->{path}, "/$action" );
29     }
30     $c->log->debug( "Loaded Regex actions:\n" . $re->draw )
31       if ( @{ $self->{compiled} } );
32 }
33
34 =head2 $self->match( $c, $path )
35
36 =cut
37
38 sub match {
39     my ( $self, $c, $path ) = @_;
40
41     return if $self->SUPER::match( $c, $path );
42
43     # Check path against plain text first
44
45     foreach my $compiled ( @{ $self->{compiled} || [] } ) {
46         if ( my @snippets = ( $path =~ $compiled->{re} ) ) {
47             next unless $compiled->{action}->match($c);
48             $c->req->action( $compiled->{path} );
49             $c->req->match($path);
50             $c->req->snippets( \@snippets );
51             $c->action( $compiled->{action} );
52             $c->namespace( $compiled->{action}->namespace );
53             return 1;
54         }
55     }
56
57     return 0;
58 }
59
60 =head2 $self->register( $c, $action )
61
62 =cut
63
64 sub register {
65     my ( $self, $c, $action ) = @_;
66     my $attrs = $action->attributes;
67     my @register = @{ $attrs->{'Regex'} || [] };
68
69     foreach my $r (@register) {
70         $self->register_path( $c, $r, $action );
71         $self->register_regex( $c, $r, $action );
72     }
73
74     return 1 if @register;
75     return 0;
76 }
77
78 =head2 $self->register_regex($c, $re, $action)
79
80 =cut
81
82 sub register_regex {
83     my ( $self, $c, $re, $action ) = @_;
84     push(
85         @{ $self->{compiled} },    # and compiled regex for us
86         {
87             re     => qr#$re#,
88             action => $action,
89             path   => $re,
90         }
91     );
92 }
93
94 =head1 AUTHOR
95
96 Matt S Trout
97 Sebastian Riedel, C<sri@cpan.org>
98
99 =head1 COPYRIGHT
100
101 This program is free software, you can redistribute it and/or modify it under
102 the same terms as Perl itself.
103
104 =cut
105
106 1;