1 package MooseX::Singleton::Role::Meta::Method::Constructor;
4 override _initialize_body => sub {
8 # the %options should also include a both
9 # a call 'initializer' and call 'SUPER::'
10 # options, which should cover approx 90%
11 # of the possible use cases (even if it
12 # requires some adaption on the part of
13 # the author, after all, nothing is free)
15 $source .= "\n" . 'my $class = shift;';
18 . 'my $existing = do { no strict "refs"; no warnings "once"; \${"$class\::singleton"}; };';
19 $source .= "\n" . 'return ${$existing} if ${$existing};';
21 $source .= "\n" . 'return $class->Moose::Object::new(@_)';
25 . $self->associated_metaclass->name . '\';';
27 $source .= $self->_generate_params( '$params', '$class' );
28 $source .= $self->_generate_instance( '$instance', '$class' );
29 $source .= $self->_generate_slot_initializers;
31 $source .= ";\n" . $self->_generate_triggers();
32 $source .= ";\n" . $self->_generate_BUILDALL();
34 $source .= ";\n" . 'return ${$existing} = $instance';
35 $source .= ";\n" . '}';
36 warn $source if $self->options->{debug};
38 my $attrs = $self->_attributes;
41 = map { $_->can('type_constraint') ? $_->type_constraint : undef }
44 my @type_constraint_bodies
45 = map { defined $_ ? $_->_compiled_type_constraint : undef; }
48 my ( $code, $e ) = $self->_compile_code(
53 '@type_constraints' => \@type_constraints,
54 '@type_constraint_bodies' => \@type_constraint_bodies,
59 "Could not eval the constructor :\n\n$source\n\nbecause :\n\n$e",
60 error => $e, data => $source )
63 $self->{'body'} = $code;
66 # Ideally we'd be setting this in the constructor, but the new() methods in
67 # what the parent classes are not well-factored.
69 # This is all a nasty hack, though. We need to fix Class::MOP::Inlined to
70 # allow constructor class roles to say "if the parent class has role X,
72 override _expected_method_class => sub {
75 my $super_value = super();
76 if ( $super_value eq 'Moose::Object' ) {
77 for my $parent ( map { Class::MOP::class_of($_) }
78 $self->associated_metaclass->superclasses ) {
80 if $parent->is_anon_class
81 && grep { $_->name eq 'Moose::Object' }
82 map { Class::MOP::class_of($_) } $parent->superclasses;
99 MooseX::Singleton::Role::Meta::Method::Constructor - Constructor method role for MooseX::Singleton
103 This role overrides the generated object C<new> method so that it returns the
104 singleton if it already exists.