File Coverage

blib/lib/Bot/ChatBots/MojoPlugin.pm
Criterion Covered Total %
statement 33 34 97.0
branch 1 2 50.0
condition 8 13 61.5
subroutine 8 8 100.0
pod 3 3 100.0
total 53 60 88.3


line stmt bran cond sub pod time code
1             package Bot::ChatBots::MojoPlugin;
2 2     2   119124 use strict;
  2         5  
  2         51  
3 2     2   9 use warnings;
  2         2  
  2         79  
4             { our $VERSION = '0.009'; }
5              
6 2     2   397 use Bot::ChatBots::Utils qw< load_module >;
  2         7  
  2         96  
7              
8 2     2   12 use Mojo::Base 'Mojolicious::Plugin';
  2         2  
  2         17  
9              
10             has [qw< app instances >];
11              
12             sub helper_name {
13 3     3 1 145 my $self = shift;
14 3   66     26 (my $name = lc(ref $self || $self)) =~ s{.*::}{}mxs;
15 3         21 return "chatbots.$name";
16             }
17              
18             sub add_instance {
19 1     1 1 2 my $self = shift;
20 1         5 my $module = load_module(shift, ref $self);
21 1 50 33     28010 my @args = (@_ && ref($_[0])) ? %{$_[0]} : @_;
  0         0  
22 1         5 my $instance = $module->new(@args, app => $self->app);
23 1         935 push @{$self->instances}, $instance;
  1         4  
24 1         6 return $instance;
25             } ## end sub add_instance
26              
27             sub register {
28 2     2 1 859 my ($self, $app, $conf) = @_;
29 2   100     8 $conf //= {};
30 2   33     7 my $helper_name = $conf->{helper_name} // $self->helper_name;
31              
32             # initialize object
33 2         10 $self->app($app);
34 2         18 $self->instances([]);
35              
36             # add helper to be usable
37 2     1   21 $app->helper($helper_name => sub { return $self });
  1         1099  
38              
39             # initialize with instances passed on the fly
40 2   100     186 $self->add_instance(@$_) for @{$conf->{instances} // []};
  2         16  
41              
42 2         11 $app->log->debug("helper $helper_name registered");
43              
44 2         314 return $self;
45             } ## end sub register
46              
47             1;
48             __END__