Catalyst::Action: Good Magic

jk2addict on 2007-05-30T02:42:08

I'm not sure how I managed to get this far into Handel/Mango Catalyst bits without ever knowing/understanding the magic that is Catalyst::Action.

The requirement was easy: add a :FormFile attribute to the Mango controllers so one could override the default form used with actions like create/edit:

sub edit : Local FormFile('/path/to/form.yml') {
    my $form = $self->form;
};


I surfed through things I knew futzed with actions. Controller::FormBuilder, Action:REST, etc. They all seemed large, or complicated, esp when you don't grok what the hell is really going on behind the scenes. After a pointer to $c->action->attribute by JMax, it all became quite clear; and easy:

First, just add an attribute parser to the controller:

sub _parse_FormFile_attr {
    my ($self, $c, $name, $value) = @_;

if (my $form = $self->_load_form_from_file($c, $value)) { return Form => $form; };

return; };


This saves the form the 'Form' attribute for the current sub/action. Then it's just a matter of sucking out the attribute for the current action when requested:

    if (exists $c->action->attributes->{'Form'}) {
        $form = $c->action->attributes->{'Form'}->[-1];
    };


That's it. Sure, there are more way to skin this cat, especially if you go all out on an :ActionClass(). But it got me where I needed to go without a whole lot of code.