6 use Test::More tests => 23;
10 Some examples of triggers and how they can
11 be used to manage parent-child relationships.
26 # if the parents last-name changes
27 # then so do all the childrens
28 foreach my $child ( @{ $self->children } ) {
29 $child->last_name( $self->last_name );
35 ( is => 'rw', isa => 'ArrayRef', default => sub { [] } );
36 __PACKAGE__->meta->make_immutable();
50 # if the parent is changed,..
52 $self->last_name( $self->parent->last_name );
60 default => sub { (shift)->parent->last_name }
62 __PACKAGE__->meta->make_immutable();
65 my $parent = Parent->new( last_name => 'Smith' );
66 isa_ok( $parent, 'Parent' );
68 is( $parent->last_name, 'Smith',
69 '... the parent has the last name we expected' );
71 $parent->children( [ map { Child->new( parent => $parent ) } ( 0 .. 3 ) ] );
73 foreach my $child ( @{ $parent->children } ) {
74 is( $child->last_name, $parent->last_name,
75 '... parent and child have the same last name ('
80 $parent->last_name('Jones');
81 is( $parent->last_name, 'Jones', '... the parent has the new last name' );
83 foreach my $child ( @{ $parent->children } ) {
84 is( $child->last_name, $parent->last_name,
85 '... parent and child have the same last name ('
92 my $parent2 = Parent->new( last_name => 'Brown' );
93 isa_ok( $parent2, 'Parent' );
97 my $orphan = pop @{ $parent->children };
99 # and then the new parent adopts it
101 $orphan->parent($parent2);
103 foreach my $child ( @{ $parent->children } ) {
104 is( $child->last_name, $parent->last_name,
105 '... parent and child have the same last name ('
110 isnt( $orphan->last_name, $parent->last_name,
111 '... the orphan child does not have the same last name anymore ('
112 . $parent2->last_name
114 is( $orphan->last_name, $parent2->last_name,
115 '... parent2 and orphan child have the same last name ('
116 . $parent2->last_name
119 # make sure that changes still will not propagate
121 $parent->last_name('Miller');
122 is( $parent->last_name, 'Miller',
123 '... the parent has the new last name (again)' );
125 foreach my $child ( @{ $parent->children } ) {
126 is( $child->last_name, $parent->last_name,
127 '... parent and child have the same last name ('
132 isnt( $orphan->last_name, $parent->last_name,
133 '... the orphan child is not affected by changes in the parent anymore' );
134 is( $orphan->last_name, $parent2->last_name,
135 '... parent2 and orphan child have the same last name ('
136 . $parent2->last_name