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