Created
March 17, 2021 11:10
-
-
Save j1n3l0/349cb42fd3329fc6e672b4251b41cb7e to your computer and use it in GitHub Desktop.
Trying to avoid mutating a readonly attribute
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
use Test2::V0 -target => 'Client'; | |
subtest 'A class with a [readonly, class_type("URI")] attribute' => sub { | |
my $uri = 'https://example.com'; | |
my $object = $CLASS->new( service_uri => $uri ); | |
is( | |
$object, | |
object { call service_uri => $uri }, | |
'should return the attribute unchanged', | |
); | |
$object->get('path'); | |
is( | |
$object, | |
object { call service_uri => $uri }, | |
'should not update the attribute at a distance', | |
); | |
}; | |
done_testing(); |
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 Client; | |
use Moo; | |
use Type::Utils qw< class_type >; | |
use Types::Standard -types; | |
use URI; | |
use experimental qw< signatures >; | |
has service_uri => ( | |
coerce => 1, | |
is => 'ro', | |
isa => class_type('URI')->plus_constructors(Str, 'new'), | |
); | |
sub get ( $self, $path ) { $self->service_uri->clone->path_segments($path) } | |
1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could use the
around
method modifier to ensure that you are only ever passed a clone on the original object:The same solution exists for Object::Pad:
But the correct way to solve this with Object::Pad (as of v0.51) is: