File Coverage

blib/lib/Async/ContextSwitcher.pm
Criterion Covered Total %
statement 19 20 95.0
branch 1 2 50.0
condition 1 3 33.3
subroutine 8 8 100.0
pod 3 3 100.0
total 32 36 88.8


line stmt bran cond sub pod time code
1 1     1   13128 use strict;
  1         1  
  1         25  
2 1     1   3 use warnings;
  1         1  
  1         20  
3 1     1   7 use v5.10;
  1         5  
4              
5             package Async::ContextSwitcher;
6              
7             our $VERSION = '0.01';
8              
9 1     1   3 use base "Exporter::Tiny";
  1         1  
  1         478  
10             our @EXPORT = qw(context cb_w_context);
11              
12             =head1 NAME
13              
14             Async::ContextSwitcher - helps track execution context in async programs
15              
16             =head1 DESCRIPTION
17              
18             This is a very simple module that helps you carry around execution context
19             in async programs.
20              
21             Idea is simple:
22              
23             =over 4
24              
25             =item * you create a new context when a new web request comes or whan a new message
26             comes from a queue or command line script starts
27              
28             =item * use L to create callbacks
29              
30             =item * correct context restored when your callbacks are called
31              
32             =item * use L to access it
33              
34             =back
35              
36              
37             You can live without it in simple applications It's not something you can deal
38              
39             =cut
40              
41              
42             our $CTX;
43              
44             sub new {
45 10     10 1 3718 my $self = shift;
46              
47 10   33     36 return $CTX = bless {@_}, ref( $self ) || $self;
48             }
49              
50             sub context() {
51 10 50   10 1 93 return $CTX if $CTX;
52 0         0 return $CTX = __PACKAGE__->new;
53             }
54              
55             sub cb_w_context(&) {
56 20     20 1 137 my $cb = $_[0];
57 20         16 my $ctx = $CTX;
58             return sub {
59 20     20   97054 $CTX = $ctx;
60 20         84 goto &$cb;
61 20         56 };
62             }
63              
64              
65             =head1 AUTHOR
66              
67             Ruslan Zakirov ERuslan.Zakirov@gmail.comE
68              
69             =head1 LICENSE
70              
71             Under the same terms as perl itself.
72              
73             =cut
74              
75             1;