I'm not sure what changed here but we need to get confess into scope
[gitmo/MooseX-Singleton.git] / lib / MooseX / Singleton / Meta / Method / Constructor.pm
CommitLineData
2b4ce4bd 1#!/usr/bin/env perl
2package MooseX::Singleton::Meta::Method::Constructor;
3use Moose;
4
5extends 'Moose::Meta::Method::Constructor';
6
0a14785c 7sub initialize_body {
2b4ce4bd 8 my $self = shift;
9 # TODO:
10 # the %options should also include a both
11 # a call 'initializer' and call 'SUPER::'
12 # options, which should cover approx 90%
13 # of the possible use cases (even if it
14 # requires some adaption on the part of
15 # the author, after all, nothing is free)
e5eff87a 16 my $source = "use Carp qw( confess );\n";
17 $source .= 'sub {';
2b4ce4bd 18 $source .= "\n" . 'my $class = shift;';
19
20 $source .= "\n" . 'my $existing = do { no strict "refs"; \${"$class\::singleton"}; };';
21 $source .= "\n" . 'return ${$existing} if ${$existing};';
22
23 $source .= "\n" . 'return $class->Moose::Object::new(@_)';
24 $source .= "\n" . ' if $class ne \'' . $self->associated_metaclass->name . '\';';
25
d871257e 26 $source .= "\n" . 'my $params = ' . $self->_generate_BUILDARGS('$class', '@_');
2b4ce4bd 27
d871257e 28 $source .= ";\n" . 'my $instance = ' . $self->meta_instance->inline_create_instance('$class');
2b4ce4bd 29
30 $source .= ";\n" . (join ";\n" => map {
31 $self->_generate_slot_initializer($_)
32 } 0 .. (@{$self->attributes} - 1));
33
a06ef25a 34 $source .= ";\n" . $self->_generate_triggers();
2b4ce4bd 35 $source .= ";\n" . $self->_generate_BUILDALL();
36
37 $source .= ";\n" . 'return ${$existing} = $instance';
38 $source .= ";\n" . '}';
39 warn $source if $self->options->{debug};
40
41 my $code;
42 {
43 # NOTE:
44 # create the nessecary lexicals
45 # to be picked up in the eval
46 my $attrs = $self->attributes;
47
48 # We need to check if the attribute ->can('type_constraint')
49 # since we may be trying to immutabilize a Moose meta class,
50 # which in turn has attributes which are Class::MOP::Attribute
51 # objects, rather than Moose::Meta::Attribute. And
52 # Class::MOP::Attribute attributes have no type constraints.
53 # However we need to make sure we leave an undef value there
54 # because the inlined code is using the index of the attributes
55 # to determine where to find the type constraint
56
57 my @type_constraints = map {
58 $_->can('type_constraint') ? $_->type_constraint : undef
59 } @$attrs;
60
61 my @type_constraint_bodies = map {
62 defined $_ ? $_->_compiled_type_constraint : undef;
63 } @type_constraints;
64
65 $code = eval $source;
66 confess "Could not eval the constructor :\n\n$source\n\nbecause :\n\n$@" if $@;
67 }
ede8dce0 68 $self->{'body'} = $code;
2b4ce4bd 69}
70
71no Moose;
72
731;