17. ThePerlReview•www.theperlreview.com
DumpingPerl6
Decorate the Dumper
my $pretty = PrettyDump.new;
class SomeClass { … }
my $SomeClass-object = SomeClass.new;
my $handler = sub ( $pretty, $ds, Int $depth = 0 ) {
...
}
$pretty.add-handler: 'SomeClass', $handler;
put $pretty.dump: $SomeClass-object;
18. ThePerlReview•www.theperlreview.com
DumpingPerl6
method dump ( $ds, Int $depth = 0 --> Str ) {
my Str $str = do {
# If the PrettyDump object has a user-defined handler
# for this type, prefer that one
if self.handles: $ds.^name {
self!handle: $ds, $depth;
}
# The object might have its own method to dump
# its structure
elsif $ds.can: 'PrettyDump' {
$ds.PrettyDump: self;
}
# If it's any sort of Numeric, we'll handle it
# and dispatch further
elsif $ds ~~ Numeric {
self!Numeric: $ds, $depth;
}
…
19. ThePerlReview•www.theperlreview.com
DumpingPerl6
# If we have a method name that matches the class, we'll
# use that.
elsif self.can: $ds.^name {
my $what = $ds.^name;
self."$what"( $ds, $depth );
}
# If the class inherits from something that we know
# about, use the most specific one that we know about
elsif self.can: any( $ds.^parents.map: *.^name ){
my Str $str = '';
for $ds.^parents.map: *.^name -> $type {
next unless self.can( $type );
$str ~= self."$type"(
$ds, $depth, "{$ds.^name}.new(", ')' );
last;
}
$str;
}
…
20. ThePerlReview•www.theperlreview.com
DumpingPerl6
# If we're this far and the object has a .Str method,
# we'll use that:
elsif $ds.can: 'Str' {
"({$ds.^name}): " ~ $ds.Str;
}
# Finally, we'll put a placeholder method there
else {
"(Unhandled {$ds.^name})"
}
};
return self!indent-string: $str, $depth;
}