Skip to content

Instantly share code, notes, and snippets.

@treyharris
Last active May 4, 2017 03:12
Show Gist options
  • Save treyharris/f26bb1a3a857be53bb8e75cfd970b14b to your computer and use it in GitHub Desktop.
Save treyharris/f26bb1a3a857be53bb8e75cfd970b14b to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl6
use v6.c;
class Example {
has $.x is rw = 0;
method double-x is rw {
return-rw Proxy.new(
:FETCH{ $!x * 2 },
:STORE(-> $, $dubX { $!x = $dubX / 2 }),
);
}
}
sub MAIN() {
use Test;
my Example $o;
lives-ok {$o .= new}, "Can construct";
is $o.x, 0, "Defaults to 0";
lives-ok {$o.x = 3}, "Can assign";
is $o.x, 3, "Assignment is correct";
my $dub-x;
lives-ok {$dub-x = $o.double-x}, "Can get from proxy";
is $dub-x, 6, "proxy returns correct value";
lives-ok {$o.double-x = 24}, "Can set using proxy";
is $o.x, 12, "proxy sets correct value";
done-testing;
}
#
# Returns:
#
# ok 1 - Can construct
# ok 2 - Defaults to 0
# ok 3 - Can assign
# ok 4 - Assignment is correct
# ok 5 - Can get from proxy
# ok 6 - proxy returns correct value
# ok 7 - Can set using proxy
# ok 8 - proxy sets correct value
# 1..8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment