make this module work with Moose 1.99 (and still work with 1.2x)
[gitmo/MooseX-Singleton.git] / lib / MooseX / Singleton / Role / Meta / Class.pm
CommitLineData
8eec3c69 1package MooseX::Singleton::Role::Meta::Class;
2use Moose::Role;
a4e5ec1e 3use MooseX::Singleton::Role::Meta::Instance;
4use MooseX::Singleton::Role::Meta::Method::Constructor;
5a0f3fa6 5
0a71b1e6 6our $VERSION = '0.25';
5a0f3fa6 7$VERSION = eval $VERSION;
109b110b 8
1de95613 9sub existing_singleton {
3822ace2 10 my ($class) = @_;
11 my $pkg = $class->name;
12
13 no strict 'refs';
14
15 # create exactly one instance
4c256923 16 if ( defined ${"$pkg\::singleton"} ) {
1de95613 17 return ${"$pkg\::singleton"};
3822ace2 18 }
19
1de95613 20 return;
21}
22
03e1b8df 23sub clear_singleton {
24 my ($class) = @_;
25 my $pkg = $class->name;
26 no strict 'refs';
27 undef ${"$pkg\::singleton"};
28}
29
0cd38a85 30override _construct_instance => sub {
1de95613 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;
3822ace2 40};
41
837c9793 42if ( $Moose::VERSION >= 1.9900 ) {
43 override _inline_params => sub {
44 my $self = shift;
45
46 return
47 'my $existing = do {',
48 'no strict "refs";',
49 'no warnings "once";',
50 '\${"$class\::singleton"};',
51 '};',
52 'return ${$existing} if ${$existing};',
53 super();
54 };
55
56 override _inline_extra_init => sub {
57 my $self = shift;
58
59 return '${$existing} = $instance;';
60 };
61}
62
2cb90d53 63no Moose::Role;
2b4ce4bd 64
109b110b 651;
66
b375b147 67__END__
68
69=pod
70
71=head1 NAME
72
8eec3c69 73MooseX::Singleton::Role::Meta::Class - Metaclass role for MooseX::Singleton
b375b147 74
75=head1 DESCRIPTION
76
8eec3c69 77This metaclass role makes sure that there is only ever one instance of an
78object for a singleton class. The first call to C<construct_instance> is run
79normally (and then cached). Subsequent calls will return the cached version.
b375b147 80
81=cut
82