| 1 | package MYDan::Node::Call; | ||
| 2 | |||
| 3 | =head1 NAME | ||
| 4 | |||
| 5 | MYDan::Node::Call - callback interface to MYDan::Node | ||
| 6 | |||
| 7 | =head1 SYNOPSIS | ||
| 8 | |||
| 9 | use MYDan::Node::Call; | ||
| 10 | |||
| 11 | my $cb = MYDan::Node::Call->new( '/callback/dir' ); | ||
| 12 | |||
| 13 | my $barbaz = $cb->run( foo => [ 1, qw( bar baz ) ] ); | ||
| 14 | my $notbarbaz = $cb->run( foo => [ 0, qw( bar baz ) ] ); | ||
| 15 | my $all = $cb->run( 'foo' ); | ||
| 16 | |||
| 17 | =cut | ||
| 18 | use strict; | ||
| 19 | use warnings; | ||
| 20 | use Carp; | ||
| 21 | |||
| 22 | use File::Spec; | ||
| 23 | use File::Basename; | ||
| 24 | |||
| 25 | =head1 CALLBACKS | ||
| 26 | |||
| 27 | Each callback must return a CODE that returns a HASH of ARRAY when invoked. | ||
| 28 | |||
| 29 | =cut | ||
| 30 | sub new | ||
| 31 | { | ||
| 32 | my ( $class, $path, %self ) = splice @_, 0, 2; | ||
| 33 | |||
| 34 | confess "undefined path" unless $path; | ||
| 35 | $path = readlink $path if -l $path; | ||
| 36 | confess "invalid path $path: not a directory" unless -d $path; | ||
| 37 | |||
| 38 | for my $path ( grep { -f $_ } glob File::Spec->join( $path, '*' ) ) | ||
| 39 | { | ||
| 40 | my $error = "invalid code: $path"; | ||
| 41 | my $name = File::Basename::basename( $path ); | ||
| 42 | |||
| 43 | $self{$name} = do $path; | ||
| 44 | confess "$error: $@" if $@; | ||
| 45 | } | ||
| 46 | bless \%self, ref $class || $class; | ||
| 47 | } | ||
| 48 | |||
| 49 | =head1 METHODS | ||
| 50 | |||
| 51 | =head3 select( %query ) | ||
| 52 | |||
| 53 | Run callback ( index of %query ) by condition ( value of %query ). | ||
| 54 | Returns results. | ||
| 55 | |||
| 56 | =cut | ||
| 57 | sub select | ||
| 58 | { | ||
| 59 | my ( $self, $name, $cond ) = splice @_; | ||
| 60 | return () unless my $code = $self->{$name}; | ||
| 61 | |||
| 62 | my $result = &$code( cond => $cond ); | ||
| 63 | return () unless $result && ref $result eq 'HASH'; | ||
| 64 | |||
| 65 | my ( $match, @val ) = shift @$cond; | ||
| 66 | |||
| 67 | unless ( @$cond ) | ||
| 68 | { | ||
| 69 | @val = values %$result; | ||
| 70 | } | ||
| 71 | elsif ( ref ( my $regex = $cond->[0] ) ) | ||
| 72 | { | ||
| 73 | my @key = $match | ||
| 74 | ? grep { $_ =~ $regex } keys %$result | ||
| 75 | : grep { $_ !~ $regex } keys %$result; | ||
| 76 | |||
| 77 | @val = @$result{ @key }; | ||
| 78 | } | ||
| 79 | else | ||
| 80 | { | ||
| 81 | @val = delete @$result{ @$cond }; | ||
| 82 | @val = values %$result unless $match; | ||
| 83 | } | ||
| 84 | @val = grep { $_ && ref $_ eq 'ARRAY' } @val; | ||
| 85 | } | ||
| 86 | |||
| 87 | =head3 run( %query ) | ||
| 88 | |||
| 89 | Alias to select(). | ||
| 90 | |||
| 91 | =cut | ||
| 92 | sub run | ||
| 93 | { | ||
| 94 | my $self = shift; | ||
| 95 | $self->select( @_ ); | ||
| 96 | } | ||
| 97 | |||
| 98 | 1; |