[Melbourne-pm] Moose - complex validation

Toby Corkindale toby.corkindale at strategicdata.com.au
Tue Jan 19 22:33:23 PST 2010


On 20/01/10 16:25, Scott Penrose wrote:
> Hey Team
>
> I have a complex moose validation, dependent on multiple inputs.
>
> e.g.
>
> package MyThing;
> use Moose;
>
> subtype 'Path'
> 	=>  as Str
> 	=>  where { -d $_ }
> 	=>  message { "Path provided must exist" };
>
> subtype 'Command'
> 	=>  as Str,
> 	# XXX how to get root ?
> 	=>  where { -f "$root/$_"&&  -x "$root/$_" },
> 	=>  message { "Command provided does not exist or is not executable " };
>
> had 'root' =>  (
> 	is =>  'ro',
> 	isa =>  'Path',
> 	default =>  '/usr/bin',
> );
>
> has 'script' =>  (
> 	is =>  'ro',
> 	isa =>  'Command',
> 	required =>  1,
> );
>
> Basically you would create the object
>
> my $o = MyThing->new(
> 	script =>  'example',
> );
>
> but you could override the default root for the scripts with:
>
> my $o = MyThing->new(
> 	script =>  'example',
> 	root =>  '/usr/sbin',
> );
>
> So... as you can see form the subtype 'Command' I am not sure how you can access the other parameter, and to define the validation order, as root would need to be done first.
>
> So... should it be done in a BUILD ?
>
> sub BUILD {
> 	my $self = shift;
> 	if (! -x $self->root . '/' . $self->script) {
> 		die "Help... script should exist in path and be executable...";
> 	}
> }
>
> I.e. is 'subtype' only for primitives ?

Hmm, it'll be hard to tell which order attributes are initialised, set, 
and checked in. ie. Even if you could get $self->root in the check 
method of script, then how do you know if it'd be checked before ->root 
was set with the /usr/sbin/ value rather than the default?

I'd go with doing the validation at another point in the code, I think, 
such as in the BUILD method, as you said.


I'm not a Moose guru though; there may be better ways.

Toby


More information about the Melbourne-pm mailing list