Questioning the Role of API Design in Perl

or Querying the Designated API of Perl Roles

If I have a role, say:

    package Dumpable {
        use autodie;
        use Role::Tiny;
        
        requires qw( to_string );
        
        sub to_file {
            my ($self, $filename, $e) = @_;
            $e //= "utf8";
            open my($fh), ">:encoding($e)", $filename;
            print {$fh}, $self->to_string;
            close $fh;
        }
    }

And if in another part of the code, I need to find out some information about that role, what should I do? Enter Role::Inspector

    use Role::Inspector qw(get_role_info);
    
    my $info = get_role_info('Dumpable');
        
    say $info->{type};       # Role::Tiny
    say for @{$info->{api}}  # to_file
                             # to_string

Currently the information provided by Role::Inspector is pretty minimal compared to the information provided by, say, Moose's role introspection. But the key selling point is that it works across all the popular role implementations for Perl, including:

What other information about roles might it provide in the future?

Well, perhaps you might want to check whether a particular role is consumable by a particular class. For example, a Moo class can consume a Moose role, and a Moose class can consume a Moo role. But while a Moo class can consume a Mouse role, a Mouse class cannot consume a Moo role. Role::Inspector might be able to provide you with a programatic go/no-go.

Do you have any ideas?

1 Comment

This looks awesome. I was just needing this the other day.

Leave a comment

About Toby Inkster

user-pic I'm tobyink on CPAN, IRC and PerlMonks.