May 18

Dispatching Through Traits

Author: s1n
Category: 01100011

In my exploration of traits, I stumbled across something that Tene created while working on the Web.pm grant. It basically uses trait_auxiliary to handle unknown sub/method traits. Here’s the actual code itself: LolDispatch.

Here’s the run-down of how this works. Be prepared, I may butcher the proper terminology or explanation since this is something that is new to me and have only started understanding it.

Line 7 defines a method called trait_auxiliary:<is>, which is what perl6 will call when an unknown sub/method trait is encountered. In this case, the trait “is” has the “http-handler” trait added to known traits. Line 8 just stashes some method information to use later.

Line 11 is the real meat of this module. It defines an exported subroutine “dispatch” that loops through the known methods and calls their postfix:() (aka operator()) method. $item<block> stashes the Closure that caused the unknown trait to be processed by trait_auxiliary:<is>.

The sample code starting in line 22 really has to go in a different file to work with Rakudo. While technically the ‘is http-handler’ trait works with methods as well, I encountered problems getting it to work.

I have an interesting use as I’m sure most people do. This basically helps remove unnecessary switch statements and dispatch tables. I simply just define my method and what the “is handler” looks like. This is really impressive, so everyone_involved++.

I wonder if there is a way (useful anyways) to combine this with a grammar.


tags: , , ,
1 comment

1 Comment so far

  1. [...] also a shell that does this work. I used Tene’s sweet dispatcher to handle the commands in the most sensible and shortest manner I could come up with. Currently, it [...]

Leave a comment