We only need local $? if we inline calls to DEMOLISH
[gitmo/Moose.git] / t / examples / record_set_iterator.t
CommitLineData
638585e1 1#!/usr/bin/perl
2
3use strict;
4use warnings;
5
a28e50e4 6use Test::More;
638585e1 7
7ff56534 8
638585e1 9{
10 package Record;
11 use Moose;
d03bd989 12
638585e1 13 has 'first_name' => (is => 'ro', isa => 'Str');
d03bd989 14 has 'last_name' => (is => 'ro', isa => 'Str');
15
638585e1 16 package RecordSet;
17 use Moose;
d03bd989 18
638585e1 19 has 'data' => (
20 is => 'ro',
d03bd989 21 isa => 'ArrayRef[Record]',
638585e1 22 default => sub { [] },
23 );
d03bd989 24
638585e1 25 has 'index' => (
26 is => 'rw',
d03bd989 27 isa => 'Int',
638585e1 28 default => sub { 0 },
29 );
d03bd989 30
638585e1 31 sub next {
32 my $self = shift;
33 my $i = $self->index;
34 $self->index($i + 1);
35 return $self->data->[$i];
36 }
d03bd989 37
638585e1 38 package RecordSetIterator;
39 use Moose;
40
41 has 'record_set' => (
42 is => 'rw',
43 isa => 'RecordSet',
44 );
45
d03bd989 46 # list the fields you want to
638585e1 47 # fetch from the current record
48 my @fields = Record->meta->get_attribute_list;
49
50 has 'current_record' => (
51 is => 'rw',
d03bd989 52 isa => 'Record',
638585e1 53 lazy => 1,
54 default => sub {
55 my $self = shift;
56 $self->record_set->next() # grab the first one
57 },
58 trigger => sub {
59 my $self = shift;
d03bd989 60 # whenever this attribute is
61 # updated, it will clear all
638585e1 62 # the fields for you.
63 $self->$_() for map { '_clear_' . $_ } @fields;
64 }
65 );
66
d03bd989 67 # define the attributes
638585e1 68 # for all the fields.
69 for my $field (@fields) {
70 has $field => (
71 is => 'ro',
d03bd989 72 isa => 'Any',
638585e1 73 lazy => 1,
d03bd989 74 default => sub {
638585e1 75 my $self = shift;
d03bd989 76 # fetch the value from
638585e1 77 # the current record
78 $self->current_record->$field();
79 },
80 # make sure they have a clearer ..
81 clearer => ('_clear_' . $field)
82 );
83 }
84
85 sub get_next_record {
86 my $self = shift;
87 $self->current_record($self->record_set->next());
88 }
89}
90
91my $rs = RecordSet->new(
92 data => [
93 Record->new(first_name => 'Bill', last_name => 'Smith'),
d03bd989 94 Record->new(first_name => 'Bob', last_name => 'Jones'),
95 Record->new(first_name => 'Jim', last_name => 'Johnson'),
638585e1 96 ]
97);
98isa_ok($rs, 'RecordSet');
99
100my $rsi = RecordSetIterator->new(record_set => $rs);
101isa_ok($rsi, 'RecordSetIterator');
102
103is($rsi->first_name, 'Bill', '... got the right first name');
104is($rsi->last_name, 'Smith', '... got the right last name');
105
106$rsi->get_next_record;
107
108is($rsi->first_name, 'Bob', '... got the right first name');
109is($rsi->last_name, 'Jones', '... got the right last name');
110
111$rsi->get_next_record;
112
113is($rsi->first_name, 'Jim', '... got the right first name');
114is($rsi->last_name, 'Johnson', '... got the right last name');
115
a28e50e4 116done_testing;