Converted this extension to use MetaRole
[gitmo/MooseX-Singleton.git] / lib / MooseX / Singleton / Role / Meta / Instance.pm
CommitLineData
109b110b 1#!/usr/bin/env perl
8eec3c69 2package MooseX::Singleton::Role::Meta::Instance;
3use Moose::Role;
109b110b 4use Scalar::Util 'weaken';
5
7afceec3 6sub get_singleton_instance {
109b110b 7 my ($self, $instance) = @_;
8
9 return $instance if blessed $instance;
ef266b1f 10
11 # optimization: it's really slow to go through new_object for every access
12 # so return the singleton if we see it already exists, which it will every
13 # single except the first.
14 no strict 'refs';
15 return ${"$instance\::singleton"} if defined ${"$instance\::singleton"};
16
e2119ce9 17 # We need to go through ->new in order to make sure BUILD and
18 # BUILDARGS get called.
19 return $instance->meta->name->new;
109b110b 20}
21
8eec3c69 22override clone_instance => sub {
7afceec3 23 my ($self, $instance) = @_;
24 $self->get_singleton_instance($instance);
8eec3c69 25};
7afceec3 26
8eec3c69 27override get_slot_value => sub {
109b110b 28 my ($self, $instance, $slot_name) = @_;
7afceec3 29 $self->is_slot_initialized($instance, $slot_name) ? $self->get_singleton_instance($instance)->{$slot_name} : undef;
8eec3c69 30};
109b110b 31
8eec3c69 32override set_slot_value => sub {
109b110b 33 my ($self, $instance, $slot_name, $value) = @_;
7afceec3 34 $self->get_singleton_instance($instance)->{$slot_name} = $value;
8eec3c69 35};
109b110b 36
8eec3c69 37override deinitialize_slot => sub {
109b110b 38 my ( $self, $instance, $slot_name ) = @_;
7afceec3 39 delete $self->get_singleton_instance($instance)->{$slot_name};
8eec3c69 40};
109b110b 41
8eec3c69 42override is_slot_initialized => sub {
109b110b 43 my ($self, $instance, $slot_name, $value) = @_;
7afceec3 44 exists $self->get_singleton_instance($instance)->{$slot_name} ? 1 : 0;
8eec3c69 45};
109b110b 46
8eec3c69 47override weaken_slot_value => sub {
109b110b 48 my ($self, $instance, $slot_name) = @_;
7afceec3 49 weaken $self->get_singleton_instance($instance)->{$slot_name};
8eec3c69 50};
109b110b 51
8eec3c69 52override inline_slot_access => sub {
109b110b 53 my ($self, $instance, $slot_name) = @_;
7afceec3 54 sprintf "%s->meta->instance_metaclass->get_singleton_instance(%s)->{%s}", $instance, $instance, $slot_name;
8eec3c69 55};
109b110b 56
2b4ce4bd 57no Moose;
58
109b110b 591;
60
b375b147 61__END__
62
63=pod
64
65=head1 NAME
66
8eec3c69 67MooseX::Singleton::Role::Meta::Instance - Instance metaclass role for MooseX::Singleton
b375b147 68
69=head1 DESCRIPTION
70
8eec3c69 71This role overrides all object access so that it gets the appropriate
72singleton instance for the class.
b375b147 73
74=cut
75