| 1 | package Bread::Board::LifeCycle::Singleton; | ||||||||||
| 2 | 57 | our $AUTHORITY = 'cpan:STEVAN'; | |||||||||
| 3 | # ABSTRACT: service role for singleton lifecycle | ||||||||||
| 4 | 57 | $Bread::Board::LifeCycle::Singleton::VERSION = '0.37'; | |||||||||
| 5 | 57 | ▶ | use Moose::Role; | ||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||
| 6 | |||||||||||
| 7 | 57 | ▶ | use Try::Tiny; | ||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||
| 8 | |||||||||||
| 9 | 57 | with 'Bread::Board::LifeCycle'; | |||||||||
| 10 | |||||||||||
| 11 | 57 | has 'instance' => ( | |||||||||
| 12 | traits => [ 'NoClone' ], | ||||||||||
| 13 | is => 'rw', | ||||||||||
| 14 | isa => 'Any', | ||||||||||
| 15 | predicate => 'has_instance', | ||||||||||
| 16 | clearer => 'flush_instance' | ||||||||||
| 17 | ); | ||||||||||
| 18 | |||||||||||
| 19 | 57 | has 'resolving_singleton' => ( | |||||||||
| 20 | traits => [ 'NoClone' ], | ||||||||||
| 21 | is => 'rw', | ||||||||||
| 22 | isa => 'Bool', | ||||||||||
| 23 | default => 0, | ||||||||||
| 24 | ); | ||||||||||
| 25 | |||||||||||
| 26 | 62 | ▶ | around 'get' => sub { | ||||||||
|
Subroutine
__ANON__: called CC=3 SCAR=11.0
| |||||||||||
| 27 | 62 | my $next = shift; | |||||||||
| 28 | 62 | my $self = shift; | |||||||||
| 29 | |||||||||||
| 30 | # return it if we got it ... | ||||||||||
| 31 | 62 | ▶ | return $self->instance if $self->has_instance; | ||||||||
|
Branch: 1 branch
| |||||||||||
| 32 | |||||||||||
| 33 | 32 | my $instance; | |||||||||
| 34 | 32 | ▶ | if ($self->resolving_singleton) { | ||||||||
|
Branch: 1 branch
| |||||||||||
| 35 | 3 | $instance = Bread::Board::Service::Deferred->new(service => $self); | |||||||||
| 36 | } | ||||||||||
| 37 | else { | ||||||||||
| 38 | 29 | $self->resolving_singleton(1); | |||||||||
| 39 | 29 | my @args = @_; | |||||||||
| 40 | 29 | ▶ | try { | ||||||||
|
Subroutine
__ANON__: called CC=1 SCAR=0.0
| |||||||||||
| 41 | # otherwise fetch it ... | ||||||||||
| 42 | 29 | $instance = $self->$next(@args); | |||||||||
| 43 | } | ||||||||||
| 44 | 0 | ▶ | catch { | ||||||||
|
Subroutine
__ANON__: not called CC=1 SCAR=6.9
| |||||||||||
| 45 | 0 | die $_; | |||||||||
| 46 | } | ||||||||||
| 47 | 29 | ▶ | finally { | ||||||||
|
Subroutine
__ANON__: called CC=1 SCAR=0.0
| |||||||||||
| 48 | 29 | $self->resolving_singleton(0); | |||||||||
| 49 | 29 | }; | |||||||||
| 50 | } | ||||||||||
| 51 | |||||||||||
| 52 | # if we get a copy, and our copy | ||||||||||
| 53 | # has not already been set ... | ||||||||||
| 54 | 32 | $self->instance($instance); | |||||||||
| 55 | |||||||||||
| 56 | # return whatever we have ... | ||||||||||
| 57 | 32 | return $self->instance; | |||||||||
| 58 | 57 | }; | |||||||||
| 59 | |||||||||||
| 60 | 57 | ▶ | no Moose::Role; 1; | ||||||||
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||||||||||
| 61 | |||||||||||
| 62 | __END__ | ||||||||||