bump version
[gitmo/MooseX-Singleton.git] / lib / MooseX / Singleton / Role / Meta / Class.pm
1 package MooseX::Singleton::Role::Meta::Class;
2 use Moose::Role;
3 use MooseX::Singleton::Role::Meta::Instance;
4 use MooseX::Singleton::Role::Meta::Method::Constructor;
5
6 our $VERSION = '0.23';
7 $VERSION = eval $VERSION;
8
9 sub existing_singleton {
10     my ($class) = @_;
11     my $pkg = $class->name;
12
13     no strict 'refs';
14
15     # create exactly one instance
16     if ( defined ${"$pkg\::singleton"} ) {
17         return ${"$pkg\::singleton"};
18     }
19
20     return;
21 }
22
23 sub clear_singleton {
24     my ($class) = @_;
25     my $pkg = $class->name;
26     no strict 'refs';
27     undef ${"$pkg\::singleton"};
28 }
29
30 override _construct_instance => sub {
31     my ($class) = @_;
32
33     # create exactly one instance
34     my $existing = $class->existing_singleton;
35     return $existing if $existing;
36
37     my $pkg = $class->name;
38     no strict 'refs';
39     return ${"$pkg\::singleton"} = super;
40 };
41
42 no Moose::Role;
43
44 1;
45
46 __END__
47
48 =pod
49
50 =head1 NAME
51
52 MooseX::Singleton::Role::Meta::Class - Metaclass role for MooseX::Singleton
53
54 =head1 DESCRIPTION
55
56 This metaclass role makes sure that there is only ever one instance of an
57 object for a singleton class. The first call to C<construct_instance> is run
58 normally (and then cached). Subsequent calls will return the cached version.
59
60 =cut
61