Created
March 14, 2018 14:02
-
-
Save ronaldxs/39ddd9a5e4c39281ddc5bf722f4fb0c3 to your computer and use it in GitHub Desktop.
mutator test using lexical as backing store instead of 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 v6; | |
# this tests that you can define mutators, that do more interesting | |
# things than merely assigning the value! | |
# For this variant we do some fakery and use a lexical as backing | |
# store instead of an attribute. | |
use Test; | |
plan 10; | |
our $count = 0; | |
class MagicVal { | |
has Int $.constant; | |
my Int $varies = 6 ; | |
method varies is rw { | |
$count++; | |
return Proxy.new( | |
# note that FETCH and STORE cannot go through the accessors | |
# of $.varies again, because that would lead to infinite | |
# recursion. Use the actual attribute here instead | |
FETCH => method () { $varies }, | |
STORE => method ($new) { $varies = $new + 1 }, | |
); | |
} | |
} | |
my $mv = MagicVal.new(:constant(6)); | |
is($mv.constant, 6, "normal attribute"); | |
is($mv.constant, 6, "normal attribute"); | |
dies-ok { $mv.constant = 7 }, "can't change a non-rw attribute"; | |
is($mv.constant, 6, "attribute didn't change value"); | |
is($count, 0, "mutator not called yet"); | |
#?rakudo skip 'RT #126198' | |
{ | |
is($mv.varies, 6, "faked object construction"); | |
is($count, 1, "accessor was called"); | |
$count = 0; | |
$mv.varies = 13; | |
is($count, 1, "mutator was called"); | |
is($mv.varies, 14, "attribute with overridden mutator"); | |
is($count, 2, "accessor and mutator were called"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment