File Coverage

blib/lib/Data/ConveyorBelt.pm
Criterion Covered Total %
statement 41 41 100.0
branch 9 12 75.0
condition 7 10 70.0
subroutine 8 8 100.0
pod 3 3 100.0
total 68 74 91.8


line stmt bran cond sub pod time code
1             package Data::ConveyorBelt;
2 2     2   598 use strict;
  2         5  
  2         77  
3 2     2   56 use 5.008_001;
  2         8  
  2         82  
4              
5 2     2   11 use base qw( Class::Accessor::Fast );
  2         13  
  2         1864  
6              
7             our $VERSION = '0.02';
8              
9             __PACKAGE__->mk_accessors(qw( getter filters ));
10              
11 2     2   6805 use Carp qw( croak );
  2         6  
  2         134  
12 2     2   12 use List::Util qw( min );
  2         4  
  2         805  
13              
14             sub new {
15 2     2 1 28 my $class = shift;
16 2         22 my $machine = $class->SUPER::new(@_);
17 2 50       31 $machine->filters( [ ] )
18             unless defined $machine->filters;
19 2         36 return $machine;
20             }
21              
22             sub add_filter {
23 2     2 1 18 push @{ shift->filters }, $_[0];
  2         8  
24             }
25              
26             sub fetch {
27 6     6 1 56 my $machine = shift;
28 6         17 my(%param) = @_;
29              
30 6 50       17 my $limit = $param{limit} or croak "limit is required";
31 6   100     24 my $offset = $param{offset} || 0;
32 6   66     18 my $chunk_size = $param{chunk_size} || $limit;
33              
34 6 50       17 my $getter = $machine->getter or croak "No getter defined";
35 6   50     46 my $filters = $machine->filters || [];
36              
37 6         30 my @data;
38 6         8 my $need = $limit + $offset;
39 6         8 my $off = 0;
40 6         13 while ( @data < $need ) {
41 13         36 my $data = $getter->( $chunk_size, $off );
42 13 100 66     162 last unless $data && @$data;
43            
44             ## If we asked for $chunk_size results and got back fewer, we know
45             ## that there aren't any more.
46 12 100       27 my $got_enough = @$data >= $chunk_size ? 1 : 0;
47              
48 12         17 for my $filter ( @$filters ) {
49 12         51 $data = $filter->( $data );
50             }
51 12         109 push @data, @$data;
52            
53 12 100       26 last unless $got_enough;
54            
55 10         28 $off += $chunk_size;
56             }
57              
58 6         60 return [ @data[ $offset .. min($#data, $need - 1) ] ];
59             }
60              
61             1;
62             __END__