From: Florian Ragwitz Date: Wed, 3 Feb 2010 13:44:03 +0000 (+0100) Subject: Properly delegate coercions for Optional[]. X-Git-Tag: 0.20~1^2 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=gitmo%2FMooseX-Types-Structured.git;a=commitdiff_plain;h=abd193e2f4fab1314a1edffb2768cd6dcf831f70 Properly delegate coercions for Optional[]. --- diff --git a/lib/MooseX/Meta/TypeCoercion/Structured/Optional.pm b/lib/MooseX/Meta/TypeCoercion/Structured/Optional.pm new file mode 100644 index 0000000..340cdc6 --- /dev/null +++ b/lib/MooseX/Meta/TypeCoercion/Structured/Optional.pm @@ -0,0 +1,25 @@ +package MooseX::Meta::TypeCoercion::Structured::Optional; + +use Moose; +extends 'Moose::Meta::TypeCoercion'; + +sub compile_type_coercion { + my ($self) = @_; + my $constraint = $self->type_constraint->type_parameter; + + $self->_compiled_type_coercion(sub { + my ($value) = @_; + return unless $constraint->has_coercion; + return $constraint->coerce($value); + }); +} + +sub has_coercion_for_type { 0 } + +sub add_type_coercions { + Moose->throw_error("Cannot add additional type coercions to Optional types"); +} + +__PACKAGE__->meta->make_immutable(inline_constructor => 0); + +1; diff --git a/lib/MooseX/Meta/TypeConstraint/Structured/Optional.pm b/lib/MooseX/Meta/TypeConstraint/Structured/Optional.pm new file mode 100644 index 0000000..09d13d9 --- /dev/null +++ b/lib/MooseX/Meta/TypeConstraint/Structured/Optional.pm @@ -0,0 +1,21 @@ +package MooseX::Meta::TypeConstraint::Structured::Optional; + +use Moose; +use MooseX::Meta::TypeCoercion::Structured::Optional; + +extends 'Moose::Meta::TypeConstraint::Parameterizable'; + +around parameterize => sub { + my $orig = shift; + my $self = shift; + + my $ret = $self->$orig(@_); + + $ret->coercion(MooseX::Meta::TypeCoercion::Structured::Optional->new(type_constraint => $ret)); + + return $ret; +}; + +__PACKAGE__->meta->make_immutable(inline_constructor => 0); + +1; diff --git a/lib/MooseX/Types/Structured.pm b/lib/MooseX/Types/Structured.pm index f5fb346..890f1f1 100644 --- a/lib/MooseX/Types/Structured.pm +++ b/lib/MooseX/Types/Structured.pm @@ -4,6 +4,7 @@ use 5.008; use Moose::Util::TypeConstraints; use MooseX::Meta::TypeConstraint::Structured; +use MooseX::Meta::TypeConstraint::Structured::Optional; use MooseX::Types::Structured::OverflowHandler; use MooseX::Types -declare => [qw(Dict Tuple Optional)]; use Sub::Exporter -setup => { exports => [ qw(Dict Tuple Optional slurpy) ] }; @@ -689,7 +690,7 @@ clean and declarative way. =cut -my $Optional = Moose::Meta::TypeConstraint::Parameterizable->new( +my $Optional = MooseX::Meta::TypeConstraint::Structured::Optional->new( name => 'MooseX::Types::Structured::Optional', package_defined_in => __PACKAGE__, parent => find_type_constraint('Item'),