File Coverage

blib/lib/WebService/Slack/IncomingWebHook.pm
Criterion Covered Total %
statement 37 37 100.0
branch 7 8 87.5
condition n/a
subroutine 10 10 100.0
pod 2 2 100.0
total 56 57 98.2


line stmt bran cond sub pod time code
1             package WebService::Slack::IncomingWebHook;
2 3     3   248554 use 5.008001;
  3         9  
  3         115  
3 3     3   14 use strict;
  3         5  
  3         88  
4 3     3   10 use warnings;
  3         11  
  3         68  
5 3     3   1654 use utf8;
  3         29  
  3         11  
6              
7 3     3   840 use JSON;
  3         11271  
  3         17  
8 3     3   1756 use Furl;
  3         57191  
  3         86  
9 3     3   21 use Carp ();
  3         3  
  3         788  
10              
11             our $VERSION = "0.01";
12              
13             sub new {
14 12     12 1 20481 my ($class, %args) = @_;
15 12 100       102 Carp::croak('required webhook url') if ! exists $args{webhook_url};
16              
17 55         116 my $self = bless {
18 11         19 map { ( $_ => $args{$_} ) } qw( webhook_url channel icon_emoji icon_url username )
19             } => $class;
20              
21 11         106 $self->{json} = JSON->new->utf8;
22 11         66 $self->{furl} = Furl->new(agent => "$class.$VERSION");
23              
24 11         515 return $self;
25             }
26              
27             sub post {
28 5     5 1 26 my ($self, %args) = @_;
29              
30 5         19 my $post_data = $self->_make_post_data(%args);
31              
32 5         91 my $res = $self->{furl}->post(
33             $self->{webhook_url},
34             ['Content-Type' => 'application/json'],
35             $self->{json}->encode($post_data),
36             );
37 5 50       10380 if (! $res->is_success) {
38 5         69 Carp::carp('post failed: '. $res->body);
39             }
40             }
41              
42             sub _make_post_data {
43 11     11   25 my ($self, %args) = @_;
44             return +{
45             (
46 55 100       105 map {
47 44 100       128 exists $args{$_} ? ( $_ => $args{$_} ) : ()
48             } qw( text pretext color fields attachments )
49             ),
50             # override if parameter specified
51             (
52             map {
53 11         18 ( $_ => exists $args{$_} ? $args{$_} : $self->{$_} )
54             } qw( channel icon_emoji icon_url username )
55             ),
56             };
57             }
58              
59             1;
60             __END__