_clear_instance and tests
[gitmo/MooseX-Singleton.git] / lib / MooseX / Singleton / Meta / Class.pm
CommitLineData
109b110b 1#!/usr/bin/env perl
2package MooseX::Singleton::Meta::Class;
3use Moose;
4use MooseX::Singleton::Meta::Instance;
0cd38a85 5use MooseX::Singleton::Meta::Method::Constructor;
109b110b 6
7extends 'Moose::Meta::Class';
8
9sub initialize {
10 my $class = shift;
11 my $pkg = shift;
12
0cd38a85 13 my $self = $class->SUPER::initialize(
109b110b 14 $pkg,
15 instance_metaclass => 'MooseX::Singleton::Meta::Instance',
0cd38a85 16 constructor_class => 'MooseX::Singleton::Meta::Method::Constructor',
109b110b 17 @_,
18 );
0cd38a85 19
20 return $self;
21}
109b110b 22
1de95613 23sub existing_singleton {
3822ace2 24 my ($class) = @_;
25 my $pkg = $class->name;
26
27 no strict 'refs';
28
29 # create exactly one instance
1de95613 30 if (defined ${"$pkg\::singleton"}) {
31 return ${"$pkg\::singleton"};
3822ace2 32 }
33
1de95613 34 return;
35}
36
03e1b8df 37sub clear_singleton {
38 my ($class) = @_;
39 my $pkg = $class->name;
40 no strict 'refs';
41 undef ${"$pkg\::singleton"};
42}
43
0cd38a85 44override _construct_instance => sub {
1de95613 45 my ($class) = @_;
46
47 # create exactly one instance
48 my $existing = $class->existing_singleton;
49 return $existing if $existing;
50
51 my $pkg = $class->name;
52 no strict 'refs';
53 return ${"$pkg\::singleton"} = super;
3822ace2 54};
55
2b4ce4bd 56no Moose;
57
109b110b 581;
59
b375b147 60__END__
61
62=pod
63
64=head1 NAME
65
66MooseX::Singleton::Meta::Class
67
68=head1 DESCRIPTION
69
70This metaclass is where the forcing of one instance occurs. The first call to
71C<construct_instance> is run normally (and then cached). Subsequent calls will
72return the cached version.
73
74=cut
75