Add support for immutable classes, by adjusting the generated constructor.
Chris Andrews [Fri, 8 Oct 2010 19:11:38 +0000 (20:11 +0100)]
lib/MooseX/UndefTolerant.pm
lib/MooseX/UndefTolerant/Constructor.pm [new file with mode: 0644]

index b026bc1..3707141 100644 (file)
@@ -4,11 +4,15 @@ use Moose qw();
 use Moose::Exporter;
 
 use MooseX::UndefTolerant::Attribute;
+use MooseX::UndefTolerant::Constructor;
 
 our $VERSION = '0.04';
 
 Moose::Exporter->setup_import_methods(
-    class_metaroles => { attribute => [ 'MooseX::UndefTolerant::Attribute' ] }
+    class_metaroles => { 
+           attribute => [ 'MooseX::UndefTolerant::Attribute' ],
+           constructor => [ 'MooseX::UndefTolerant::Constructor' ],
+    }
 );
 
 1;
diff --git a/lib/MooseX/UndefTolerant/Constructor.pm b/lib/MooseX/UndefTolerant/Constructor.pm
new file mode 100644 (file)
index 0000000..e89b609
--- /dev/null
@@ -0,0 +1,18 @@
+package MooseX::UndefTolerant::Constructor;
+use Moose::Role;
+
+around('_generate_slot_initializer', sub {
+        my $orig = shift;
+        my $self = shift;
+        my $attr = $self->_attributes->[$_[0]]->init_arg;
+
+        my $tolerant_code = 
+             qq# delete \$params->{'$attr'} unless # . 
+             qq# exists \$params->{'$attr'} && defined \$params->{'$attr'};\n#;
+
+        return $tolerant_code . $self->$orig(@_);
+});
+
+no Moose::Role;
+
+1;