[tpm] modifying methods per instance

Abram Hindle abram.hindle at softwareprocess.es
Fri May 7 23:17:54 PDT 2010


I have not tried this. I bet you can get MOOSE to do it.

What I'd try is to generate a new package where the previous class is used as base for that class.

I'd define those methods within that package and then rebless the instance.

Make a Gensym sub that can test for existence and then return a random package name;

you could generate code like this:
package SoAndSo::Prototype::Gensym::XYZABC

use base qw(SoAndSo);

*SoAndSo::Prototype::Gensym::XYZABC = $method1;
*SoAndSo::Prototype::Gensym::XYZABC = $method2;

...

bless("SoAndSo::Prototype::Gensym::XYZABC",$instance1);

Alternatively, use delegation. Set a dispatch hash and catch it using anonymous, so you don't have to play any type games.

abram



On Sat, 8 May 2010, Shaun Fryer wrote:

> Does anyone know an easy way to 'attach' *different* sets of methods to two
> *instances* of the same package?
>
> Right now I'm doing something like this fairly simplified example below.
>
> sub _attach_methods {
>   my ($self, @aVars) = @_;
>   my $class = ref $self;
>   for my $sVar (@aVars) {
>         *{ $class .'::'. $sVar } = sub {
>                 my $o = shift;
>               return $o->{$sVar} if $o->{$sVar};
>                 $o->{$sVar} = $self->_get_var($sVar);
>               return $o->{$sVar};
>             };
>   }
> }
> $instance_1->_attach_methods(qw( foo bar));
> $instance_2->_attach_methods(qw( baz quux ));
>
>
> The challenge is that @aVars above will (necessarily) be different for each
> instance according to a database driven chain of relations. In fact there
> are more than one _attach_methods() style operations being done (ie.
> _attach_these(), _attach_those() ), where each instance may have the same
> method names available, but each with different functionality.
>
> Unfortunately, at present when I add a colliding method name to an instance,
> it's the parent package method which gets over-written, thereby changing the
> functionality of the named method for all instances of the class at once,
> rather than just the one instance I'm specifically intending to manipulate.
> I've looked into using Moose/Class:MOP::Instance->meta->add_method(...), but
> I think it suffers from the same issue since it falls back to
> Class::MOP::Class.
>
> Any ideas, or am I going to need to resort to dynamically generating unique
> package suffixes for each instance?
>
> Cheers,
> --
> Shaun Fryer
>


More information about the toronto-pm mailing list