clean up and add NAME sections
[gitmo/Role-Tiny.git] / lib / Sub / Defer.pm
CommitLineData
eae82931 1package Sub::Defer;
2
3use strictures 1;
4use base qw(Exporter);
b1eebd55 5use Moo::_Utils;
eae82931 6
a165a07f 7our @EXPORT = qw(defer_sub undefer_sub);
eae82931 8
9our %DEFERRED;
10
a165a07f 11sub undefer_sub {
eae82931 12 my ($deferred) = @_;
13 my ($target, $maker, $undeferred_ref) = @{
14 $DEFERRED{$deferred}||return $deferred
15 };
16 ${$undeferred_ref} = my $made = $maker->();
a165a07f 17 if (defined($target)) {
18 no warnings 'redefine';
19 *{_getglob($target)} = $made;
20 }
eae82931 21 return $made;
22}
23
a165a07f 24sub defer_sub {
eae82931 25 my ($target, $maker) = @_;
26 my $undeferred;
27 my $deferred_string;
9187b862 28 my $deferred = sub {
a165a07f 29 goto &{$undeferred ||= undefer_sub($deferred_string)};
9187b862 30 };
eae82931 31 $deferred_string = "$deferred";
32 $DEFERRED{$deferred} = [ $target, $maker, \$undeferred ];
a165a07f 33 *{_getglob $target} = $deferred if defined($target);
eae82931 34 return $deferred;
35}
36
371;
8213644a 38
39=pod
40
0b6e5fff 41=head1 NAME
42
43Sub::Defer - defer generation of subroutines until they are first called
44
8213644a 45=head1 SYNOPSIS
46
47 use Sub::Defer;
48
49 my $deferred = defer_sub 'Logger::time_since_first_log' => sub {
50 my $t = time;
51 sub { time - $t };
52 };
53
0b6e5fff 54 Logger->time_since_first_log; # returns 0 and replaces itself
55 Logger->time_since_first_log; # returns time - $t
8213644a 56
57=head1 DESCRIPTION
58
0b6e5fff 59These subroutines provide the user with a convenient way to defer creation of
8213644a 60subroutines and methods until they are first called.
61
62=head1 SUBROUTINES
63
64=head2 defer_sub
65
66 my $coderef = defer_sub $name => sub { ... };
67
0b6e5fff 68This subroutine returns a coderef that encapsulates the provided sub - when
69it is first called, the provided sub is called and is -itself- expected to
70return a subroutine which will be goto'ed to on subsequent calls.
8213644a 71
0b6e5fff 72If a name is provided, this also installs the sub as that name - and when
73the subroutine is undeferred will re-install the final version for speed.
8213644a 74
75=head2 undefer_sub
76
77 my $coderef = undefer_sub \&Foo::name;
78
79If the passed coderef has been L<deferred|/defer_sub> this will "undefer" it.
80If the passed coderef has not been deferred, this will just return it.
81
82If this is confusing, take a look at the example in the L</SYNOPSIS>.