migrate repository to https://github.com/moose/MooseX-Singleton
[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
5a0f3fa6 5
7afceec3 6sub get_singleton_instance {
4c256923 7 my ( $self, $instance ) = @_;
109b110b 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
4c256923 22override clone_instance => sub {
23 my ( $self, $instance ) = @_;
7afceec3 24 $self->get_singleton_instance($instance);
8eec3c69 25};
7afceec3 26
4c256923 27override get_slot_value => sub {
28 my ( $self, $instance, $slot_name ) = @_;
29 $self->is_slot_initialized( $instance, $slot_name )
30 ? $self->get_singleton_instance($instance)->{$slot_name}
31 : undef;
8eec3c69 32};
109b110b 33
4c256923 34override set_slot_value => sub {
35 my ( $self, $instance, $slot_name, $value ) = @_;
7afceec3 36 $self->get_singleton_instance($instance)->{$slot_name} = $value;
8eec3c69 37};
109b110b 38
4c256923 39override deinitialize_slot => sub {
109b110b 40 my ( $self, $instance, $slot_name ) = @_;
7afceec3 41 delete $self->get_singleton_instance($instance)->{$slot_name};
8eec3c69 42};
109b110b 43
4c256923 44override is_slot_initialized => sub {
45 my ( $self, $instance, $slot_name, $value ) = @_;
7afceec3 46 exists $self->get_singleton_instance($instance)->{$slot_name} ? 1 : 0;
8eec3c69 47};
109b110b 48
4c256923 49override weaken_slot_value => sub {
50 my ( $self, $instance, $slot_name ) = @_;
7afceec3 51 weaken $self->get_singleton_instance($instance)->{$slot_name};
8eec3c69 52};
109b110b 53
4c256923 54override inline_slot_access => sub {
55 my ( $self, $instance, $slot_name ) = @_;
56 sprintf "%s->meta->instance_metaclass->get_singleton_instance(%s)->{%s}",
57 $instance, $instance, $slot_name;
8eec3c69 58};
109b110b 59
2cb90d53 60no Moose::Role;
2b4ce4bd 61
109b110b 621;
63
4e4f795a 64# ABSTRACT: Instance metaclass role for MooseX::Singleton
65
b375b147 66__END__
67
68=pod
69
b375b147 70=head1 DESCRIPTION
71
8eec3c69 72This role overrides all object access so that it gets the appropriate
73singleton instance for the class.
b375b147 74
75=cut
76