"automatically" wrapping methods.

[email protected] (Bill Moseley)
Newsgroups perl.moose
Message-ID <CAKhN_m5piyDF6dR9ia56C5euGmxT1-P9CdFn432md_hV2MfSGA@mail.gmail.com>
I have have a number of classes that include methods that need input
validation.  I use a validation class for each method which means
validation is called the same way every time its used.  That is, I have a
common pattern I'm using on a number of methods and wondering if anyone can
suggest a more clever approach so I don't end up repeating similar code.

A code example might make it clearer:

package MyModel::User;
use Moose;
extends 'MyModel::Base';


# This method is called by the consumer to create a new user,
# and the $user_data passed here is assumed to have been validated.

sub new_user {
    my ( $self, $user_data ) = @_;

    return $self->ORM_layer( 'User' )->create( $user_data );
}


# Here's the code that gets repeated for every method that requires
validation.

around new_user => sub {
    my ( $orig, $self, $args ) = @_;

    # Fetch validation instance for
    my $validation_class = $self->validation_class_for_method( 'new_user' );
    my $validation_instance = $validation_class->new( $args );

    # Throw exception object with validation failures unless data passes
validation.
    $validation_instance->thow_exception unless
$validation_instance->validates_ok;

    return;
};


So, I'm looking for a suggestion how to avoid the explicit wrapper.  One
option I was considering was something Catalyst-like with subroutine
attributes:

sub new_user : Validate {
    ...
}

Then all methods with the "Validate" attribute would automatically get
wrapped, although I'm not clear if that's the best approach or even its
implementation.

Thanks,





-- 
Bill Moseley
[email protected]
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.