File Coverage

lib/Mojolicious/Plugin/Subdispatch.pm
Criterion Covered Total %
statement 29 29 100.0
branch 12 14 85.7
condition 3 3 100.0
subroutine 7 7 100.0
pod 1 1 100.0
total 52 54 96.3


line stmt bran cond sub pod time code
1             package Mojolicious::Plugin::Subdispatch;
2 1     1   1453 use Mojo::Base 'Mojolicious::Plugin';
  1         3  
  1         11  
3              
4 1     1   239 use Mojo::UserAgent::Transactor;
  1         2  
  1         12  
5              
6             our $VERSION = '0.04';
7              
8             has app => sub { die 'not registered!' };
9             has transactor => sub { Mojo::UserAgent::Transactor->new };
10             has 'base_url';
11              
12             sub _subdispatch {
13 9     9   35 my ($self, $method, @args) = @_;
14              
15             # extract post data
16 9 100 100     66 my $post_data = (uc $method eq 'POST' and ref $args[-1] eq 'HASH') ?
17             pop @args : undef;
18              
19             # build request url
20 9         240 my $url = $self->app->url_for(@args);
21 9 100       13020 $url->base($self->base_url) if defined $self->base_url;
22              
23             # build transaction
24 9 100       322 my $tx = $post_data ?
25             $self->transactor->tx($method => $url => form => $post_data)
26             : $self->transactor->tx($method => $url);
27              
28             # dispatch
29 9         8534 $self->app->handler($tx);
30              
31 9         63508 return $tx;
32             }
33              
34             # Mojo::UserAgent like interface
35             # we don't really need post_form, but Mojo::UA uses it.
36             {
37 1     1   368 no strict 'refs';
  1         2  
  1         307  
38             for my $name (qw(DELETE GET HEAD POST POST_FORM PUT)) {
39             *{__PACKAGE__ . '::' . lc($name)} = sub {
40 6     6   16 my $self = shift;
41 6 50       31 my $method = $name eq 'POST_FORM' ? 'POST' : $name;
42 6         29 return $self->_subdispatch($method => @_)->res;
43             };
44             }
45             }
46              
47             sub register {
48 2     2 1 6674 my ($self, $app, $conf) = @_;
49 2         52 $self->app($app);
50              
51             # does your base are belong to us?
52 2 100       28 if (defined $conf->{base_url}) {
53 1         3 my $base_url = $conf->{base_url};
54 1 50       12 $base_url = Mojo::URL->new($base_url) unless ref $base_url;
55 1         495 $self->base_url($base_url);
56             }
57              
58             # add subdispatch helper
59             $app->helper(subdispatch => sub {
60 9     9   55631 my $s = shift;
61              
62             # Mojo::UserAgent like interface usage
63 9 100       80 return $self unless @_;
64              
65             # direct subdispatch call
66 3         16 return $self->_subdispatch(@_);
67 2         28 });
68             }
69              
70             1;
71             __END__