Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard way to selectively inherit methods from a Perl superclass?

Or: Is there a standard way to create subclass but make certain methods from the superclass yield a "Can't locate object method" error when called?

For example, if My::Foo inherits from My::Bar, and My::Bar has a method called dostuff, calling Foo->new->dostuff would die with the "Can't locate object method" error in some non-contrived/hackish way.

like image 494
Richard Simões Avatar asked Dec 07 '25 04:12

Richard Simões


2 Answers

If the superclass is a Moose class you could use remove_method.

package My::Foo;
use Moose;
extends 'My::Bar';

# some code here

my $method_name = 'method_to_remove';

__PACKAGE__->meta->remove_method($method_name);

1;

This is documented in Class::MOP::Class and should work with MooseX::NonMoose but i am not sure.

like image 69
matthias krull Avatar answered Dec 08 '25 18:12

matthias krull


You can create dummy methods in your child class that intercept the method calls and die.

package My::Foo;
our @ISA = 'My::Bar';
use Carp ();

for my $method qw(dostuff ...) {
    no strict 'refs';
    *$method = sub {Carp::croak "no method '$method' on '$_[0]'"};
}   

You could even write a module to do this:

package No::Method;
use Carp ();
sub import {
    my $class = shift;
    my $caller = caller;

    for my $method (@_) {
        no strict 'refs';
        *{"$caller\::$method"} = sub {
              Carp::croak "no method '$method' on '$_[0]'"
         };
    }
}  

And then to use it:

package My::Foo;
our @ISA = 'My::Bar';
use No::Method qw(dostuff);
like image 31
Eric Strom Avatar answered Dec 08 '25 19:12

Eric Strom