Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: Moose(X) create my own Collection

by tobyink (Abbot)
on Jan 19, 2012 at 09:38 UTC ( #948730=note: print w/replies, xml ) Need Help??

in reply to Moose(X) create my own Collection

You don't want to define MyCollection as a class. Define it as a parameterised role instead. IIRC, there is some MooseX::Declare syntactic sugar for parameterised roles, but I can't remember exactly how it goes, and it's undocumented.

package MyCollection; use MooseX::Role::Parameterized; parameter type => ( isa => 'ClassName', required => 1, ); parameter attr => ( isa => 'Str', required => 1, ); role { my $p = shift; my ($type, $attr) = ($p->type, $p->attr); has $attr => ( is => 'rw', isa => "HashRef[$type]", traits => ['Hash'], defaults => sub { {} } ); method "summon_$attr" => sub { my $self = shift; foreach my $item (values %{ $self->$attr }) { $item->summon if $item->does('Summonable'); } }; }; # and we'll use MooseX::Declare syntax for the rest... role Summonable { requires 'name'; method summon { say "Come here, ", $self->name; } } class Child with Summonable { has name => ( is => 'ro', isa => 'Str' ); } class Parent { with MyCollection => { type => 'Child', attr => 'children' }; } my $me = Parent->new; $me->children->{isabel} = Child->new(name => 'Isabel'); $me->children->{elliott} = Child->new(name => 'Elliott'); $me->summon_children;

The above is untested, and probably has some syntax errors lurking somewhere, but it should give you an idea of how it can be done.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://948730]
Discipulus desease the question..
[shmem]: Discipulus: war/peace is a question of fuel gauge position...
[Discipulus]: yes i saw your cell brother..
[Discipulus]: but now fuel is cheap and they still make some war.
[Discipulus]: capitalism is able to go to war by cycle, even.
[shmem]: some? are you jokin' ?

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2017-04-29 21:57 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (534 votes). Check out past polls.