remove shbang from modules
[gitmo/MooseX-Singleton.git] / lib / MooseX / Singleton / Role / Meta / Instance.pm
1 package MooseX::Singleton::Role::Meta::Instance;
2 use Moose::Role;
3 use Scalar::Util 'weaken';
4
5 sub get_singleton_instance {
6     my ($self, $instance) = @_;
7
8     return $instance if blessed $instance;
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
16     # We need to go through ->new in order to make sure BUILD and
17     # BUILDARGS get called.
18     return $instance->meta->name->new;
19 }
20
21 override clone_instance => sub  {
22     my ($self, $instance) = @_;
23     $self->get_singleton_instance($instance);
24 };
25
26 override get_slot_value => sub  {
27     my ($self, $instance, $slot_name) = @_;
28     $self->is_slot_initialized($instance, $slot_name) ? $self->get_singleton_instance($instance)->{$slot_name} : undef;
29 };
30
31 override set_slot_value => sub  {
32     my ($self, $instance, $slot_name, $value) = @_;
33     $self->get_singleton_instance($instance)->{$slot_name} = $value;
34 };
35
36 override deinitialize_slot => sub  {
37     my ( $self, $instance, $slot_name ) = @_;
38     delete $self->get_singleton_instance($instance)->{$slot_name};
39 };
40
41 override is_slot_initialized => sub  {
42     my ($self, $instance, $slot_name, $value) = @_;
43     exists $self->get_singleton_instance($instance)->{$slot_name} ? 1 : 0;
44 };
45
46 override weaken_slot_value => sub  {
47     my ($self, $instance, $slot_name) = @_;
48     weaken $self->get_singleton_instance($instance)->{$slot_name};
49 };
50
51 override inline_slot_access => sub  {
52     my ($self, $instance, $slot_name) = @_;
53     sprintf "%s->meta->instance_metaclass->get_singleton_instance(%s)->{%s}", $instance, $instance, $slot_name;
54 };
55
56 no Moose;
57
58 1;
59
60 __END__
61
62 =pod
63
64 =head1 NAME
65
66 MooseX::Singleton::Role::Meta::Instance - Instance metaclass role for MooseX::Singleton
67
68 =head1 DESCRIPTION
69
70 This role overrides all object access so that it gets the appropriate
71 singleton instance for the class.
72
73 =cut
74