From: Dave Rolsky Date: Sun, 21 Jun 2009 20:32:40 +0000 (-0500) Subject: add use of BUILDARGS to exercises for section 01 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=f7da468c69a669dae20adddc9fa6aca50d6d2718;p=gitmo%2Fmoose-presentations.git add use of BUILDARGS to exercises for section 01 --- diff --git a/moose-class/exercises/answers/01-classes/Person.pm b/moose-class/exercises/answers/01-classes/Person.pm index 5e79748..00e0f16 100644 --- a/moose-class/exercises/answers/01-classes/Person.pm +++ b/moose-class/exercises/answers/01-classes/Person.pm @@ -5,6 +5,20 @@ use Moose; has first_name => ( is => 'rw' ); has last_name => ( is => 'rw' ); +sub BUILDARGS { + my $class = shift; + + if ( @_ == 1 && 'ARRAY' eq ref $_[0] ) { + return { + first_name => $_[0]->[0], + last_name => $_[0]->[1], + }; + } + else { + return $class->SUPER::BUILDARGS(@_); + } +} + sub full_name { my $self = shift; diff --git a/moose-class/exercises/t/01-classes.t b/moose-class/exercises/t/01-classes.t index b781dc9..dd11fab 100644 --- a/moose-class/exercises/t/01-classes.t +++ b/moose-class/exercises/t/01-classes.t @@ -11,6 +11,12 @@ # method should return the first and last name separated by a string # ("Jon Smith"). # +# Write a BUILDARGS method for this class which allows the caller to +# pass a two argument array reference. These should be assigned to the +# first and last name respectively. +# +# Person->new( [ 'Lisa', 'Smith' ] ); +# # Create an Employee class in lib/Employee.pm # # The Employee class is a subclass of Person diff --git a/moose-class/exercises/t/lib/MooseClass/Tests.pm b/moose-class/exercises/t/lib/MooseClass/Tests.pm index 0ac9921..aba82cf 100644 --- a/moose-class/exercises/t/lib/MooseClass/Tests.pm +++ b/moose-class/exercises/t/lib/MooseClass/Tests.pm @@ -265,6 +265,14 @@ sub person01 { is( $person->full_name, 'Bilbo Baggins', 'full_name() is correctly implemented' ); + + $person = Person->new( [ qw( Lisa Smith ) ] ); + is( $person->first_name, 'Lisa', 'set first_name from two-arg arrayref' ); + is( $person->last_name, 'Smith', 'set last_name from two-arg arrayref' ); + + eval { Person->new( sub { 'foo' } ) }; + like( $@, qr/\QSingle parameters to new() must be a HASH ref/, + 'Person constructor still rejects bad parameters' ); } sub employee01 {