3
0
mirror of https://github.com/pragma-/pbot.git synced 2024-10-02 01:18:40 +02:00
pbot/PBot/Registerable.pm
Pragmatic Software d955bfa06c Add centralized configuration registry module
Allows changing of bot configuration values without needing to restart
bot instance or needing to edit pbot.pl script.

Registry will initially be populated with default values from pbot.pl,
but if a registry file exists then the registry values will take
precedence over the pbot.pl values. For instance, if you regset the
bot trigger to '%' then the trigger will be '%' even if pbot.pl has '!'
or something else explicitly set.

Some registry items can have trigger hooks associated with them.  For
instance, the irc->botnick registry entry has a change_botnick_trigger
associated with it which changes the IRC nick on the server when a new
value is set via regset/regadd.

Tons of other fixes and improvements throughout.
2014-05-17 20:08:19 +00:00

85 lines
1.5 KiB
Perl

# File: Registerable.pm
# Author: pragma_
#
# Purpose: Provides functionality to register and execute one or more subroutines.
package PBot::Registerable;
use warnings;
use strict;
use Carp ();
sub new {
if(ref($_[1]) eq 'HASH') {
Carp::croak("Options to Registerable should be key/value pairs, not hash reference");
}
my ($class, %conf) = @_;
my $self = bless {}, $class;
$self->initialize(%conf);
return $self;
}
sub initialize {
my $self = shift;
$self->{handlers} = [];
}
sub execute_all {
my $self = shift;
foreach my $func (@{ $self->{handlers} }) {
my $result = &{ $func->{subref} }(@_);
return $result if defined $result;
}
return undef;
}
sub execute {
my $self = shift;
my $ref = shift;
if(not defined $ref) {
Carp::croak("Missing reference parameter to Registerable::execute");
}
foreach my $func (@{ $self->{handlers} }) {
if($ref == $func || $ref == $func->{subref}) {
return &{ $func->{subref} }(@_);
}
}
return undef;
}
sub register {
my $self = shift;
my $subref;
if(@_) {
$subref = shift;
} else {
Carp::croak("Must pass subroutine reference to register()");
}
my $ref = { subref => $subref };
push @{ $self->{handlers} }, $ref;
return $ref;
}
sub unregister {
my $self = shift;
my $ref;
if(@_) {
$ref = shift;
} else {
Carp::croak("Must pass subroutine reference to unregister()");
}
@{ $self->{handlers} } = grep { $_ != $ref && $_->{subref} != $ref } @{ $self->{handlers} };
}
1;