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