Skip to content

Commit

Permalink
Adding eval fix
Browse files Browse the repository at this point in the history
  • Loading branch information
phochste committed Oct 10, 2018
1 parent 1dfa5c4 commit c359b55
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
52 changes: 52 additions & 0 deletions lib/Catmandu/Fix/eval.pm
@@ -0,0 +1,52 @@
package Catmandu::Fix::eval;

use Catmandu::Sane;

our $VERSION = '1.10';

use Catmandu::Fix;
use Catmandu::Util qw(:is data_at);
use Moo;

with 'Catmandu::Fix::Inlineable';

has path => (is => 'ro' , required => 1);

around BUILDARGS => sub {
my ($orig, $class, $path) = @_;
$orig->($class, path => $path);
};

sub fix {
my ($self, $data) = @_;
my $code = data_at($self->path, $data);
return $data unless $code && (is_string($code) || is_array_ref($code));
$code = [ $code ] unless is_array_ref($code);
my $fixer = Catmandu::Fix->new(fixes => $code);
return $data unless $fixer;
$fixer->fix($data);
}

1;

__END__
=pod
=head1 NAME
Catmandu::Fix::eval - evaluate stored in a variable
=head1 SYNOPSIS
# fixes => 'add_field(foo,bar)'
eval(fixes) # foo => bar
# fixer => ['add_field(foo,bar)','upcase(foo)']
eval(fixes) # foo => BAR
=head1 SEE ALSO
L<Catmandu::Fix>
=cut
32 changes: 32 additions & 0 deletions t/Catmandu-Fix-eval.t
@@ -0,0 +1,32 @@
#!/usr/bin/env perl

use strict;
use warnings;
use Test::More;
use Test::Exception;

my $pkg;

BEGIN {
$pkg = 'Catmandu::Fix::eval';
use_ok $pkg;
}

is_deeply $pkg->new('fixes')->fix({}),+{};

is_deeply $pkg->new('fixes')->fix({fixes => 'add_field(foo,bar)'}),
+{fixes => 'add_field(foo,bar)',foo => 'bar'};

is_deeply $pkg->new('fixes')->fix({fixes => ['add_field(foo,bar)']}),
+{fixes => ['add_field(foo,bar)'],foo => 'bar'};

is_deeply $pkg->new('fixes')->fix({fixes => [
'add_field(foo,bar)',
'upcase(foo)'
]}),
+{fixes => ['add_field(foo,bar)','upcase(foo)'],foo => 'BAR'};

is_deeply $pkg->new('fixes')->fix({fixes => {foo => 'bar'}}) ,
+{fixes => {foo => 'bar'}};

done_testing;

0 comments on commit c359b55

Please sign in to comment.