1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
|
package Catmandu::Fix::Bind::with;
use Catmandu::Sane;
our $VERSION = '1.2024';
use Moo;
use Clone ();
use Catmandu::Util;
use namespace::clean;
use Catmandu::Fix::Has;
with 'Catmandu::Fix::Bind', 'Catmandu::Fix::Bind::Group';
has path => (fix_opt => 1);
sub zero {
my ($self) = @_;
[];
}
sub unit {
my ($self, $data) = @_;
defined $self->path ? Catmandu::Util::data_at($self->path, $data) : $data;
}
sub bind {
my ($self, $mvar, $code) = @_;
if (Catmandu::Util::is_hash_ref($mvar)) {
my $copy = Clone::clone($mvar);
$copy = $code->($copy);
if (ref($copy) eq 'reject') {
#map { delete $mvar->{$_} } (keys %$mvar);
%$mvar = ();
}
else {
%$mvar = %$copy;
}
return $mvar;
}
elsif (Catmandu::Util::is_array_ref($mvar)) {
my $idx = 0;
for my $item (@$mvar) {
$item = $code->($item);
if (ref($item) eq 'reject') {
splice(@$mvar, $idx, 1);
}
$idx++;
}
return $mvar;
}
else {
return $self->zero;
}
}
sub reject {
my ($self, $var) = @_;
return bless $var, 'reject' if ref($var);
return bless \$var, 'reject';
}
1;
__END__
=pod
=head1 NAME
Catmandu::Fix::Bind::with - a binder that computes Fix-es in the context of a path
=head1 SYNOPSIS
# Input data
data:
- name: patrick
- name: nicolas
# Fix
do with(path:data)
if all_match(name,nicolas)
reject()
end
end
# will produce
data:
- name: patrick
=head1 DESCRIPTION
The C<with> bind allows to run fixes in the scope of a path.
Given a deep nested data structure :
my:
deep:
field:
name: James Brown
these two fixes are equal:
add_field(my.deep.field.style, funk)
do with(path:my.deep.field)
add_field(style,funk)
end
=head1 CONFIGURATION
=head2 path
The path to a list in the data.
=head1 SEE ALSO
L<Catmandu::Fix::Bind>
=cut
|