Created
June 15, 2016 14:54
-
-
Save ksurent/7fca076d1fd5c383f7e32fb324d700e8 to your computer and use it in GitHub Desktop.
A simple example of using Moose's ability to automagically install delegation by introspecting roles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Role; | |
use Moose::Role; | |
requires "delegated_method"; | |
has provided_attribute => ( | |
is => "ro", | |
isa => "Str", | |
lazy => 1, | |
builder => "_build_provided_attribute", | |
); | |
sub _build_provided_attribute { "PROVIDED ATTRIBUTE" } | |
sub provided_method { | |
print "PROVIDED METHOD\n"; | |
} | |
package Class2; | |
use Moose; | |
with "Role"; | |
sub delegated_method { | |
print "DELEGATED METHOD\n"; | |
} | |
sub _private_method { | |
print "PRIVATE METHOD\n"; | |
} | |
__PACKAGE__->meta->make_immutable; | |
package Class; | |
use Moose; | |
has delegator => ( | |
is => "ro", | |
does => "Role", | |
handles => "Role", | |
lazy => 1, | |
builder => "_build_delegator", | |
); | |
sub _build_delegator { | |
Class2->new; | |
} | |
__PACKAGE__->meta->make_immutable; | |
package main; | |
use strict; | |
use warnings; | |
my $object = Class->new; | |
# implemented in Class2, delegated | |
$object->delegated_method; | |
# composed into Class2, delegated | |
$object->provided_method; | |
# methods not required by Role are not delegated | |
#$object->_private_method; | |
# Moose is smart enough to distinguish between provided and generated methods | |
#print $object->provided_attribute, "\n"; | |
# but not smart enough to realise that a provided method sometimes is not meant for delegation | |
# (the following works but I'd argue it shouldn't) | |
#print $object->_build_provided_attribute, "\n"; | |
# this still works, of course: | |
print $object->delegator->provided_attribute, "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment