Moose to The Resque

Well not really but it did save me a good deal of time. I have been slowly putting together a small stand alone web app with Mojolicious to trunly demonstate what I have been doing with all these Moose posts.

Well I was just setting up a controller (using Mojolicious::Lite here to save space) and was creating my first form and like I many I have created before I started with a validator; something like this


app->validator->add_check(range => sub {
  my ($validation, $name, $value, $min, $max) = @_;
  return $value < $min || $value > $max;
});

post '/create' => sub {
my $self = shift;
my $validation = $self->validation;
$validation->required('strength')->size(1, 2)->range (3,18);
$validation->required('intelligence')->size(1, 2)->range (3,18);

and then I though 'I am just recreating all that validation that I already have in my 'RPG::ADD::Character' class' So why not let Moose validate itself?

Well before I ran out and wrote a bunch of validation code based on my Moose Class I went to Map of Cpan and spent a few mins looking to see if someone else has done the coding for me.

Well sure enough somebody has (well there goes weeks worth of blog posts) and it can be found here Mojolicious::Plugin::ValidateMoose. So after a few second installing I gave it a try.

So with a HTLM page that looks like this

validate_1.jpg

I changed my app a little to the following


plugin 'Mojolicious::Plugin::ValidateMoose';

post '/create' => sub {
my $self = shift;
use RPG::ADD::Character;
my $class = $self->validate_moose('RPG::ADD::Character');

if ($self->stash('invalid_form_elements')){
$self->render('index');
}
else {
$self->stash(me => $class);
$self->render('character');
}

};

changed my inputs a little to fail and my original index form to display the error and got this

validate_2.jpg

So great.

Whats nice is if the object does not fail then you get a instace of the object you can throw into the stash and play with on a page. One thing I really like is this plugin works for all the inputs to the class not just the fist fail like you would get with a simple '->new()'. All of the fails are loading into a hash so I can do a many are there are on the class. For example if I submit a blank form I get this

validate_3.jpg

So two, or is that three birds, with one stone. Well going to keep this one in my Playbook

keep_calm_and_love_moose_print_or_poster-rcaa925f4af0e4ba5b4ef03a9e7a73d07_wvc_8byvr_512.jpg


Leave a comment

About byterock

user-pic Long time Perl guy, a few CPAN mods allot of work on DBD::Oracle and a few YAPC presentations