Trust issues
On IRC japhb told us that he needs a class to trust another class that can’t see the to be trusted class.
class B {…}
class A {
trusts B;
}
class B {
}
This is nice and simple and allows B to call private methods on A. Sadly, that only works if A
and B
reside in the same file because a forward declaration will cause a compile time error, unless we define the declared type in the same compilation unit.
Method resolution is a runtime creature in Raku. By carefully looking at the code, we can learn where Rakudo stores what we need to cheat with.
class A {
has $!a = 'private';
method !a { $!a }
}
multi sub trait_mod:<is>(Mu:U \obj, :$spying!) {
A.^add_trustee(obj);
}
class B is spying(A) {
has A $.a = A.new;
method m { say $!a!A::a }
}
B.new.m;
Luckily, the trait is
operates quite early at compile time, so we don’t mess up method dispatch. I’m not feeling to bad poking with a trait where I should not peek. We can always move quickly into NQP-land and break things.
method cheating {
use nqp;
say nqp::getattr($.a, A, 'a');
}
As shown above, privacy is a matter of politeness. What leaves the question, if forcing a forward declaration to be resolved locally, to be a good design decision. I shall ponder to file a problem solving issue.
Why not just use the .^add_trustee meta method? Then you don’t have to resort to NQP.