Commit | Line | Data |
109b110b |
1 | #!/usr/bin/env perl |
2 | package MooseX::Singleton::Meta::Instance; |
3 | use Moose; |
4 | use Scalar::Util 'weaken'; |
5 | |
6 | extends 'Moose::Meta::Instance'; |
7 | |
7afceec3 |
8 | sub get_singleton_instance { |
109b110b |
9 | my ($self, $instance) = @_; |
10 | |
11 | return $instance if blessed $instance; |
ef266b1f |
12 | |
13 | # optimization: it's really slow to go through new_object for every access |
14 | # so return the singleton if we see it already exists, which it will every |
15 | # single except the first. |
16 | no strict 'refs'; |
17 | return ${"$instance\::singleton"} if defined ${"$instance\::singleton"}; |
18 | |
68213909 |
19 | return $instance->meta->construct_instance; |
109b110b |
20 | } |
21 | |
7afceec3 |
22 | sub clone_instance { |
23 | my ($self, $instance) = @_; |
24 | $self->get_singleton_instance($instance); |
25 | } |
26 | |
109b110b |
27 | sub get_slot_value { |
28 | my ($self, $instance, $slot_name) = @_; |
7afceec3 |
29 | $self->is_slot_initialized($instance, $slot_name) ? $self->get_singleton_instance($instance)->{$slot_name} : undef; |
109b110b |
30 | } |
31 | |
32 | sub set_slot_value { |
33 | my ($self, $instance, $slot_name, $value) = @_; |
7afceec3 |
34 | $self->get_singleton_instance($instance)->{$slot_name} = $value; |
109b110b |
35 | } |
36 | |
37 | sub deinitialize_slot { |
38 | my ( $self, $instance, $slot_name ) = @_; |
7afceec3 |
39 | delete $self->get_singleton_instance($instance)->{$slot_name}; |
109b110b |
40 | } |
41 | |
42 | sub is_slot_initialized { |
43 | my ($self, $instance, $slot_name, $value) = @_; |
7afceec3 |
44 | exists $self->get_singleton_instance($instance)->{$slot_name} ? 1 : 0; |
109b110b |
45 | } |
46 | |
47 | sub weaken_slot_value { |
48 | my ($self, $instance, $slot_name) = @_; |
7afceec3 |
49 | weaken $self->get_singleton_instance($instance)->{$slot_name}; |
109b110b |
50 | } |
51 | |
52 | sub inline_slot_access { |
53 | my ($self, $instance, $slot_name) = @_; |
7afceec3 |
54 | sprintf "%s->meta->instance_metaclass->get_singleton_instance(%s)->{%s}", $instance, $instance, $slot_name; |
109b110b |
55 | } |
56 | |
2b4ce4bd |
57 | no Moose; |
58 | |
109b110b |
59 | 1; |
60 | |
b375b147 |
61 | __END__ |
62 | |
63 | =pod |
64 | |
65 | =head1 NAME |
66 | |
67 | MooseX::Singleton::Meta::Instance |
68 | |
69 | =head1 DESCRIPTION |
70 | |
71 | This instance metaclass manages attribute access and storage. When accessing an |
72 | attribute, it will convert a bare package to its cached singleton instance |
73 | (creating it if necessary). |
74 | |
75 | =cut |
76 | |