Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: Changing the Class Name of a Moose Instance

by tobyink (Abbot)
on Oct 03, 2012 at 16:45 UTC ( #997097=note: print w/replies, xml ) Need Help??

in reply to Changing the Class Name of a Moose Instance

use v5.14; use Moose (); sub with_traits_and_fancy_schmancy_name { my ($name, $base, @roles) = @_; return $base unless @roles; return 'Moose::Meta::Class'->create( $name, superclasses => [$base], roles => \@roles, )->name; } package Person { use Moose; has name => (is => 'ro', isa => 'Str'); sub add_numbers { my $self = shift; my $sum; $sum += $_ for @_; return $sum; } }; package Inumerate { use Moose::Role; around add_numbers => sub { confess "I'm no good at maths"; }; }; my $bob = with_traits_and_fancy_schmancy_name( 'Idiot', 'Person' => qw( Inumerate ), )->new(name => 'Robert'); $bob->add_numbers(1, 2, 3);

Update: previously I didn't include a very good example usage.

perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Replies are listed 'Best First'.
Re^2: Changing the Class Name of a Moose Instance
by jandrew (Chaplain) on Oct 03, 2012 at 17:02 UTC

    Thanks++, that works.

    Update: I just ran the updated example and I like the 'confess' output that includes Idiot::add_numbers('Idiot=HASH(0x337cf38)', 1, 2, 3). Nice touch

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://997097]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2018-05-21 10:11 GMT
Find Nodes?
    Voting Booth?