1 package Method::Generate::Constructor;
5 use base qw(Class::Tiny::Object);
9 sub register_attribute_specs {
10 my ($self, %spec) = @_;
11 @{$self->{attribute_specs}||={}}{keys %spec} = values %spec;
15 sub all_attribute_specs {
16 $_[0]->{attribute_specs}
19 sub accessor_generator {
20 $_[0]->{accessor_generator}
25 my $package = $self->{package};
26 defer_sub "${package}::new" => sub {
27 unquote_sub $self->generate_method(
28 $package, 'new', $self->{attribute_specs}, { no_install => 1 }
35 my ($self, $into, $name, $spec, $quote_opts) = @_;
36 foreach my $no_init (grep !exists($spec->{$_}{init_arg}), keys %$spec) {
37 $spec->{$no_init}{init_arg} = $no_init;
39 local $self->{captures} = {};
40 my $body = ' my $class = shift;'."\n";
41 $body .= $self->_generate_args;
42 $body .= $self->_check_required($spec);
43 $body .= ' my $new = bless({}, $class);'."\n";
44 $body .= $self->_assign_new($spec);
45 $body .= $self->_fire_triggers($spec);
46 $body .= ' return $new;'."\n";
48 "${into}::${name}" => $body,
49 $self->{captures}, $quote_opts||{}
55 q{ my $args = ref($_[0]) eq 'HASH' ? $_[0] : { @_ };}."\n";
59 my ($self, $spec) = @_;
61 NAME: foreach my $name (keys %$spec) {
62 my $attr_spec = $spec->{$name};
64 next NAME unless defined(my $i = $attr_spec->{init_arg});
69 return '' unless @init;
70 ' @{$new}{qw('.join(' ',@slots).')} = @{$args}{qw('.join(' ',@init).')};'
75 my ($self, $spec) = @_;
77 map $spec->{$_}{init_arg},
78 grep $spec->{$_}{required},
80 return '' unless @required_init;
81 ' if (my @missing = grep !exists $args->{$_}, qw('
82 .join(' ',@required_init).')) {'."\n"
83 .q{ die "Missing required arguments: ".join(', ', sort @missing);}."\n"
88 my ($self, $spec) = @_;
90 [ $_, $spec->{$_}{init_arg}, $spec->{$_}{trigger} ]
91 } grep { $spec->{$_}{init_arg} && $spec->{$_}{trigger} } keys %$spec;
92 my $acc = $self->accessor_generator;
93 my $captures = $self->{captures};
95 foreach my $name (keys %$spec) {
96 my ($init, $trigger) = @{$spec->{$name}}{qw(init_arg trigger)};
97 next unless $init && $trigger;
98 my ($code, $add_captures) = $acc->generate_trigger(
99 $name, '$new', $acc->generate_simple_get('$new', $name), $trigger
101 @{$captures}{keys %$add_captures} = values %$add_captures;
102 $fire .= " ${code} if exists \$args->{${\perlstring $init}};\n";