search spec components factored out of T365
[catagits/Reaction.git] / lib / Reaction / InterfaceModel / Search / UpdateSpec.pm
1 package Reaction::InterfaceModel::Search::UpdateSpec;
2
3 use Moose::Role;
4 use Method::Signatures::Simple;
5 use aliased 'Reaction::InterfaceModel::Search::Spec', 'SearchSpec';
6 use namespace::clean -except => 'meta';
7
8 has '+target_model' => (isa => SearchSpec);
9
10 requires '_reflection_info';
11
12 override BUILDARGS => method () {
13   my $args = super;
14   my $model = $args->{target_model};
15   my $reflected = $self->_reflection_info;
16   foreach my $attr (@{$reflected->{empty}||[]}) {
17     if ($model->${\"has_${attr}"}) {
18       $args->{$attr} = $model->$attr;
19     } else {
20       $args->{$attr} = '';
21     }
22   }
23   foreach my $attr (@{$reflected->{normal}||[]}) {
24     my $has = $model->can("has_${attr}")||sub {1};
25     $args->{$attr} = $model->$attr if $model->$has;
26   }
27   $args;
28 };
29
30 method do_apply () {
31   my $data = $self->parameter_hashref;
32   my $spec = $self->target_model;
33   foreach my $name (keys %$data) {
34     # note: this assumes plain is => 'rw' attrs on the backend
35     # which is safe since we control it. Also, we assume '' means
36     # clear - this may not be safe later but is for now
37     if (length(my $value = $data->{$name})) {
38       $spec->$name($value);
39     } else {
40       $spec->${\"clear_${name}"};
41     }
42   }
43   $spec;
44 }
45
46 1;
47