split out can_sync_to_action from sync_to_action in anticipation of new password...
[catagits/Reaction.git] / lib / Reaction / UI / ViewPort / Field / Role / Mutable.pm
index cb48dce..0d39eec 100644 (file)
@@ -14,52 +14,62 @@ role Mutable, which {
     clearer => 'clear_value',
   );
   has needs_sync => (is => 'rw', isa => 'Int', default => 0);
-  has message    => (is => 'rw', isa => 'Str');
-
-  around value => sub {
-    my $orig = shift;
-    my $self = shift;
-    if (@_ && !ref($_[0]) && defined($_[0]) && !length($_[0])) { # ''
-      unless ($self->value_is_required) {
-        return $self->clear_value;
-      }
-    }
-    $self->$orig(@_);
-  };
+  #predicates are autmagically generated for lazy and non-required attrs
+  has message => (is => 'rw', isa => 'Str', clearer => 'clear_message');
 
   after clear_value => sub {
-    shift->needs_sync(1);
+    my $self = shift;
+    $self->clear_message if $self->has_message;
+    $self->needs_sync(1);
   };
 
   implements adopt_value => as {
     my ($self) = @_;
+    $self->clear_message if $self->has_message;
     $self->needs_sync(1); # if $self->has_attribute;
   };
 
-  implements sync_to_action => as {
-    my ($self) = @_;
-    return unless $self->needs_sync && $self->has_value;
+  implements can_sync_to_action => as {
+    my $self = shift;
+    return 1 unless $self->needs_sync;
     my $attr = $self->attribute;
 
     if ($self->has_value) {
       my $value = $self->value;
       if (my $tc = $attr->type_constraint) {
         $value = $tc->coercion->coerce($value) if ($tc->has_coercion);
-        #my $error = $tc->validate($self->value); # should we be checking against $value?
-        my $error = $tc->validate($value);
-        if (defined $error) {
+        if (defined (my $error = $tc->validate($value))) {
           $self->message($error);
           return;
         }
       }
+    } else {
+      return if $attr->is_required;
+    }
+    return 1;
+  };
+
+  implements sync_to_action => as {
+    my ($self) = @_;
+    return unless $self->needs_sync;
+    return unless $self->can_sync_to_action;
+
+    my $attr = $self->attribute;
+
+    if ($self->has_value) {
+      my $value = $self->value;
+      if (my $tc = $attr->type_constraint) {
+        #this will go away when we have moose dbic. until then though...
+        $value = $tc->coercion->coerce($value) if ($tc->has_coercion);
+      }
       my $writer = $attr->get_write_method;
       confess "No writer for attribute" unless defined($writer);
       $self->model->$writer($value);
     } else {
-      my $predicate = $attr->get_predicate;
+      my $predicate = $attr->predicate;
       confess "No predicate for attribute" unless defined($predicate);
       if ($self->model->$predicate) {
-        my $clearer = $attr->get_clearer;
+        my $clearer = $attr->clearer;
         confess "${predicate} returned true but no clearer for attribute"
           unless defined($clearer);
         $self->model->$clearer;