File: import.pm

package info (click to toggle)
libcatmandu-perl 1.2024-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,552 kB
  • sloc: perl: 17,037; makefile: 24; sh: 1
file content (67 lines) | stat: -rw-r--r-- 1,457 bytes parent folder | download
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
package Catmandu::Fix::import;

use Catmandu::Sane;

our $VERSION = '1.2024';

use Catmandu;
use Catmandu::Util::Path qw(as_path);
use Moo;
use namespace::clean;
use Catmandu::Fix::Has;

with 'Catmandu::Fix::Builder';

has path       => (fix_arg => 1);
has name       => (fix_arg => 1);
has delete     => (fix_opt => 1);
has ignore_404 => (fix_opt => 1);
has opts       => (fix_opt => 'collect');

sub _build_fixer {
    my ($self)     = @_;
    my $path       = as_path($self->path);
    my $name       = $self->name;
    my $opts       = $self->opts;
    my $delete     = $self->delete;
    my $ignore_404 = $self->ignore_404;
    $path->updater(
        sub {
            my $val = $_[0];
            try {
                $val = Catmandu->importer($name, variables => $val, %$opts)
                    ->first;
            }
            catch_case [
                'Catmandu::HTTPError' => sub {
                    if ($_->code eq '404' && $ignore_404) {$val = undef}
                    else                                  {$_->throw}
                }
            ];

            return $val if defined $val;
            return undef, 1, $delete;
        }
    );
}

1;

__END__

=pod

=head1 NAME

Catmandu::Fix::import - change the value of a HASH key or ARRAY index by replacing
its value with imported data

=head1 SYNOPSIS

   import(foo.bar, JSON, file: "http://foo.com/bar.json", data_path: data.*)

=head1 SEE ALSO

L<Catmandu::Fix>

=cut