From: Kent Fredric Date: Mon, 3 Aug 2015 03:15:16 +0000 (+1200) Subject: Document how to pass new attribute values at instance-role application time X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=gitmo%2FMoose.git;a=commitdiff_plain;h=f3eac4e8e19809324ba5b92f8cf37eda8819a09d Document how to pass new attribute values at instance-role application time --- diff --git a/lib/Moose/Manual/Roles.pod b/lib/Moose/Manual/Roles.pod index 51cf93d..009a2ea 100644 --- a/lib/Moose/Manual/Roles.pod +++ b/lib/Moose/Manual/Roles.pod @@ -326,4 +326,45 @@ normal Moose role combination system. We recommend using this function to apply roles to an object. This is what Moose uses internally when you call C. +=head2 Handling required attributes for roles. + +Application of some roles will require additional parameters being specified to +satisfy them, for example: + + { + package Car; + use Moose; + } + { + package Breakable; + use Moose::Role; + + has 'breakable_parts' => ( is => 'ro', required => 1 ); + } + + my $car = Car->new; + + # next line dies with: Attribute (breakable_parts) is required + apply_all_roles( $car, 'Breakable' ); + +This will require passing the additional parameters at application time as +follows: + + apply_all_roles( $car, 'Breakable' => { + rebless_params => { + # Parameters to 'Breakable' + breakable_parts => [qw( tires wheels windscreen )], + } + }); + +Obviously, this interface is better simplified as a method on C: + + sub make_breakable { + my ( $self, %params ) = @_; + apply_all_roles($self, 'Breakable', { rebless_params => \%params }); + } + + my $car = Car->new(); + $car->make_breakable( breakable_parts => [qw( tires wheels windscreen )] ); + =cut