Roles and BUILD

5 views
Skip to first unread message

Ingo Blechschmidt

unread,
May 16, 2005, 11:10:10 AM5/16/05
to perl6-l...@perl.org
Hi,

are Roles allowed to contain submethods and does especially the BUILD
submethod
work as I presume in the following code?

class IRC::Bot {
has Array %:handler;

method add_handler(Str $event, Code $callback) {
push %:handler{$event}: $callback;
}

...;
}

role IRC::Bot::JoinOnInvite {
submethod BUILD() {
./add_handler("INVITE", -> Str $channel {
./join($channel);
});
}
}

role IRC::Bot::SayHelloOnJoin {
submethod BUILD() {
./add_handler("JOIN", -> Str $nick {
./msg($nick, "Hi $nick!");
});
}
}

class MyBot {
is IRC::Bot;
does IRC::Bot::JoinOnInvite;
does IRC::Bot::SayHelloOnJoin;
}
my MyBot $bot .= new;
# Are IRC::Bot::JoinOnInvite::BUILD and
# IRC::Bot::SayHelloOnJoin::BUILD called?

And:
my IRC::Bot $bot .= new;
# Up to now, no BUILDs of any role is called.
$bot does IRC::Bot::SayHelloOnJoin;
# Is IRC::Bot::SayHelloOnJoin's BUILD called now?


--Ingo

--
Linux, the choice of a GNU | To understand recursion, you must first
generation on a dual AMD | understand recursion.
Athlon! |

Larry Wall

unread,
May 16, 2005, 11:55:36 AM5/16/05
to perl6-l...@perl.org
On Mon, May 16, 2005 at 03:10:10PM +0000, Ingo Blechschmidt wrote:
: my MyBot $bot .= new;
: # Are IRC::Bot::JoinOnInvite::BUILD and
: # IRC::Bot::SayHelloOnJoin::BUILD called?

Yes, role BUILD submethods are magically composed into the class's
BUILD method somehow (or at least called at the appropriate time).

: And:

: my IRC::Bot $bot .= new;
: # Up to now, no BUILDs of any role is called.
: $bot does IRC::Bot::SayHelloOnJoin;
: # Is IRC::Bot::SayHelloOnJoin's BUILD called now?

Seems like a reasonable thing in general. If you're going to be
adding state to an object, it really ought to be initialized correctly
(though in this case you seem to be adding the state outside the
object itself, which is also fine).

Larry

Brent 'Dax' Royal-Gordon

unread,
May 17, 2005, 12:07:45 AM5/17/05
to perl6-l...@perl.org
On 5/16/05, Larry Wall <la...@wall.org> wrote:
> Yes, role BUILD submethods are magically composed into the class's
> BUILD method somehow (or at least called at the appropriate time).

Could this be a feature of all submethods, not just BUILD? (DESTROY,
for instance, would need it too...)

--
Brent 'Dax' Royal-Gordon <br...@brentdax.com>
Perl and Parrot hacker

Reply all
Reply to author
Forward
0 new messages