in reply to Remove roles for an object in perl moose

If the role has been applied to the instance (rather than its class), then you can certainly remove all such roles by reblessing it back into its original class:

$class->meta->rebless_instance($object);

But this sounds like a bad idea.

Perhaps instead of adding and removing roles you should consider using delegation.

class Teacher { method teach () { ... } } class ClassRoom { has teacher => ( is => 'rw', handles => ['teach'], clearer => 'vacate', ); } my $room1 = ClassRoom->new; eval { $room1->teach; # dies (no teacher!) }; # Instead of adding a role, # give the classroom an object # that it can delegate to... # $room1->teacher( Teacher->new ); $room1->teach; # ok! # Instead of removing the role, # remove the object that's being # delegated to... $room1->vacate; eval { $room1->teach; # dies (no teacher!) };

Roles are awesome and it's tempting to use them for everything, but maybe delegation is something more appropriate for the problem you're trying to solve. Step back and explain your wider problem and we might be able to give you other ideas of how to approach it.

use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

Replies are listed 'Best First'.
Re^2: Remove roles for an object in perl moose
by davido (Cardinal) on Sep 28, 2013 at 16:22 UTC

    So is delegation a form of composition where the object exposes the api of one of its composite participants?


    Dave

      The handles => ['teach'] bit is really just a shortcut for writing something like:

      sub teach { (shift->teacher or die)->teach(@_); }

      It's not especially sophisticated - e.g. it doesn't make can("teach") return false if teacher is not set. But it's a useful technique for observing the Law of Demeter.

      use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name
        Hi Tobyink,

        Thanks fr such a wonderful

        reply. The problem actually is, lets assume we ve two modules named car.pm and bike.pm both contain same methods with exactly same names but different functionalities . There is a super class called vehicle.pm which actually decides methods in car.pm should be called or bike.pm should be called based on certain param from the calling script.

        this switching should be dynamic like in run time we should be able decide to switch between car and bike objects . So we have decided to assign roles to vehicle.pm to switch roles to Car and bike and one role being at a time. So only there was a need to remove one role when other s active. Please comment