Skip to content

Instantly share code, notes, and snippets.

@Xliff
Last active September 7, 2020 10:10
Show Gist options
  • Save Xliff/b27f77e3353915248ff09e9c28c4ed68 to your computer and use it in GitHub Desktop.
Save Xliff/b27f77e3353915248ff09e9c28c4ed68 to your computer and use it in GitHub Desktop.
Easing delegation

I'm trying to programmatically delegate via code, mainly to not have to keep track of a "handles" trait with lots of method names.

So I want to try and add all of the methods in SOUP::Server to the first attribute in my SOUP::Test::Server class. I've come up with this bit of code, but it's not working:

    sub getMethodNames(Mu \o) {
       o.^methods( :local )
        .grep({
          .name ne <BEGIN BUILD BUILDALL DESTROY TWEAK>.any &&
          .package.^name eq o.^name
        })
        .map( *.name )
        .unique
    }

    trait_mod:<handles>(
      self.^attributes[0],
      sub { getMethodNames(SOUP::Server) }
   );
   self.^attributes[0].apply_handles( SOUP::Test::Server );

This is being done at run time. Is it too late in the object lifetime for this to work?

@Xliff
Copy link
Author

Xliff commented Sep 7, 2020

Aha!

Thanks to @dakkar on #raku, this looks to be the best solution:

class B {
  has A $!a handles *;
}

Will delegate all methods of class A to class B. Thanks again, @dakkar++

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment