Catalyst Advent - Day 8 - Don't Repeat Yourself

DRY is a central principle in Catalyst, yet there is one piece of code that is identical in 90% of all Catalyst applications.

  sub end : Private {
      my ($self,$c) = @_;
      return 1 if $c->res->body;
      return 1 if $c->response->status =~ /^3\d\d$/;
      $c->forward( 'MyApp::View::TT' );

Basically, we want to render a template unless we already have a response, or are redirecting.

Catalyst::Plugin::DefaultEnd to the rescue!

So, rather than doing this again and again, I've made a plugin for you to use. sure, it's not much code, but at least it's one function less to worry about.

Here's how to use it:

1. Open up

2. Add the DefaultEnd plugin like this:

  use Catalyst qw/-Debug DefaultEnd Static::Simple/;

3. There is no step 3 :)

As an added bonus, you can now set dump_info=1 as a url parameter to force the end action to die, and display the debug info. Note that this is only provided in Debug mode.

By default, DefaultEnd will forward to the first view it can find. If you have more than one view, you might want to specifiy the active one, by setting $c->config->{view}.

If you need to add more things to your end action, you can extend it like this.

  sub end : Private {
      my ( $self, $c ) = @_;

      ... #code before view

      $c->NEXT::end( $c );

      ... #code after view

Have fun!

-- marcus