Commits

juster committed 000939e

Adds before and after filters.

Before filters modify the request. After filters modify the response.
They are also hierarchal. Filters at the root happen for all requests.

  • Participants
  • Parent commits 3e48cb4

Comments (0)

Files changed (2)

File ex/test.psgi

 use Web::Deux;
 our @ROUTES = qw( hello=Hello );
 
+sub __AFTER__
+{
+    my ( $resp ) = @_;
+    return <<"END_HTML";
+<html>
+ <head><title>Helloooo!</title></head>
+ <body><h1>$resp</h1></body>
+</html>
+END_HTML
+}
+
 sub __GET__ ()
 {
-    "Well, hello to you too, buster... I never!"
+    'Who the heck are you?';
 }
 
 # Error "handlers" are inheritable by using @ISA.
     'Huh?'
 }
 
+#-----------------------------------------------------------------------------
+
 package Hello::World;
+
 our @ISA = 'Root'; # inherits Root::__404__
 our @ROUTES;
 
     "That is so cliche... poser!";
 }
 
+#-----------------------------------------------------------------------------
+
 package Hello;
-our @ISA = 'Root';
+
+our @ISA    = 'Root';
 our @ROUTES = qw( world=Hello::World );
 
+sub __BEFORE__
+{
+    my ( $paths_ref ) = @_;
+    $paths_ref->[0] = 'Buddy' if @$paths_ref == 0;
+    return;
+}
+
 sub __GET__
 {
     my ( $who ) = join q{ }, @_;
-    $who ||= 'Buddy';
     "Hello, ${who}!";
 }
 

File lib/Web/Deux.pm

         ( $match, $fwdpkg ) = $subname =~ m{ \A ( [^=]+ ) = (.*) }xms;
         if ( $match ) {
             next FROUTE_LOOP if lc $match ne lc $pathcomp;
-            return $fwdpkg->dispatch( @_ ) 
+            return _call_with_filters( $pkg,
+                                       sub { shift; $fwdpkg->dispatch( @_ ) },
+                                       $pathcomp, @_ );
         }
 
         ( $method, $match ) = $subname =~
         return $pkg->error( 404 ) unless @_ == $argcount;        
     }
 
-    return $coderef->( @_ );
+    # After we have checked for errors, we can apply our filters...
+    return _call_with_filters( $pkg, sub { $coderef->( @_ ) }, @_ );
+}
+
+sub _call_with_filters
+{
+    my $pkg      = shift;
+    my $code_ref = shift;
+
+    my $reqfilter = do {
+        no strict 'refs';
+        *{"${pkg}::__BEFORE__"}{'CODE'}
+    };
+    if ( $reqfilter ) {
+        my $paths_ref = [ @_ ];
+        my $resp      = $reqfilter->( $paths_ref );
+        return $resp if $resp;
+        @_ = @$paths_ref;
+    }
+
+    my $resp = $code_ref->( @_ );
+
+    my $respfilter = do {
+        no strict 'refs';
+        *{"${pkg}::__AFTER__"}{'CODE'}
+    };
+    if ( $respfilter ) {
+        return $respfilter->( $resp );
+    }
+
+    return $resp;
 }
 
 #-----------------------------------------------------------------------------