[Melbourne-pm] Moose 'isa' property prevents setting attribute to undef

Stephen Thirlwall stephen.thirlwall at strategicdata.com.au
Sun Sep 16 21:05:00 PDT 2012


The easiest way to do what you want is:

	isa => 'Maybe[AG::Dataset]'
or
	isa => 'Undef|AG::Dataset'

Then undef is also an accepted value for dataset.
(no idea which is the preferred syntax)


David's suggestion has the benefit/drawback of preventing dataset
from being inadvertently set to undef.

	$foo->dataset($value_is_undef)


There is also:

	predicate => 'has_dataset'

which does what is says.


It also makes sense to use both the clearer/predicate and nullable type,
in the (rare?) case where you need to distinguish unset from set-to-undef.

eg.

my $foo = Foo->new;  	# $foo->has_dataset is false
$foo->dataset($x);	# $foo->has_dataset is true
$foo->dataset(undef);	# $foo->has_dataset is still true
$foo->clear_dataset;	# $foo->has_dataset is false again


Steve


On 17/09/12 1:19 PM, David Warring wrote:
> Hi Ian,
> You most likely want to delete the attribute entirely, rather than setting it to undef.
>
> One way is to define a clearer property for it:
>
> package Foo;
>
> use Moose;
>
> # ...
>
> has 'dataset' => (
>      is => 'rw',
>      isa => 'AG::Dataset',
>      required => 0,
>      clearer => 'clear_dataset',
> );
>
> then ...
>
> my $foo = Foo->new();
> $foo->dataset(bless {}, 'AG::Dataset');
>
> use YAML::Syck; print YAML::Syck::Dump({foo => $foo});
>
> $foo->clear_dataset;
>
> use YAML::Syck; print YAML::Syck::Dump({foo => $foo});
>
> - David
>
> On Mon, Sep 17, 2012 at 12:52 PM, Ian Macdonald <ickphum at gmail.com <mailto:ickphum at gmail.com>> wrote:
>
>     Hi,
>
>     We've got a Moose class with this attribute:
>
>
>     has 'dataset' => (
>          is => 'rw',
>          isa => 'AG::Dataset',
>          required => 0,
>     );
>
>     It's not required so you can happily create objects without supplying a value for it, but once you've done so, you can't then remove/clear it via "$object->dataset(undef)" :
>
>          Attribute (dataset) does not pass the type constraint because: Validation failed for 'AG::Dataset' failed with value undef (not isa AG::Dataset)
>
>     Given that it's legal to have undefs in there initially it seems funny not to be allowed to revert to that state. Am I missing another property which will allow this? I'd rather not have to remove the validation or do it manually, seems like a backward step.
>
>     Thanks,
>     --
>     Ian Macdonald
>
>
>     _______________________________________________
>     Melbourne-pm mailing list
>     Melbourne-pm at pm.org <mailto:Melbourne-pm at pm.org>
>     http://mail.pm.org/mailman/listinfo/melbourne-pm
>
>
>
>
> _______________________________________________
> Melbourne-pm mailing list
> Melbourne-pm at pm.org
> http://mail.pm.org/mailman/listinfo/melbourne-pm
>



More information about the Melbourne-pm mailing list