Tenative switch to a generated DEMOLISHALL - see rest of message for caveats
[gitmo/Moo.git] / lib / Moo / Object.pm
CommitLineData
b1eebd55 1package Moo::Object;
6c74d087 2
3use strictures 1;
4
098a367b 5our %NO_BUILD;
6our $BUILD_MAKER;
56ffe19d 7our $DEMOLISH_MAKER;
098a367b 8
6c74d087 9sub new {
10 my $class = shift;
098a367b 11 $NO_BUILD{$class} and
12 return bless({ ref($_[0]) eq 'HASH' ? %{$_[0]} : @_ }, $class);
13 $NO_BUILD{$class} = !$class->can('BUILD') unless exists $NO_BUILD{$class};
14 $NO_BUILD{$class}
15 ? bless({ ref($_[0]) eq 'HASH' ? %{$_[0]} : @_ }, $class)
077bd026 16 : do {
5d349892 17 my $proto = ref($_[0]) eq 'HASH' ? $_[0] : { @_ };
18 bless({ %$proto }, $class)->BUILDALL($proto);
077bd026 19 };
098a367b 20}
21
0123201b 22# Inlined into Method::Generate::Constructor::_generate_args() - keep in sync
a17be455 23sub BUILDARGS {
24 my $class = shift;
25 if ( scalar @_ == 1 ) {
26 unless ( defined $_[0] && ref $_[0] eq 'HASH' ) {
27 die "Single parameters to new() must be a HASH ref"
b512e801 28 ." data => ". $_[0] ."\n";
a17be455 29 }
30 return { %{ $_[0] } };
31 }
32 elsif ( @_ % 2 ) {
bbed1e70 33 die "The new() method for $class expects a hash reference or a key/value list."
b512e801 34 . " You passed an odd number of arguments\n";
a17be455 35 }
36 else {
37 return {@_};
38 }
39}
40
098a367b 41sub BUILDALL {
42 my $self = shift;
43 $self->${\(($BUILD_MAKER ||= do {
44 require Method::Generate::BuildAll;
45 Method::Generate::BuildAll->new
46 })->generate_method(ref($self)))}(@_);
6c74d087 47}
48
c2cc003f 49sub DESTROY {
50 my $self = shift;
51
52 return unless $self->can('DEMOLISH'); # short circuit
53
54 require Moo::_Utils;
55
56 my $e = do {
57 local $?;
58 local $@;
59 eval {
60 # DEMOLISHALL
61
56ffe19d 62 $self->DEMOLISHALL($Moo::_Utils::_in_global_destruction);
c2cc003f 63 };
64 $@;
65 };
66
67 no warnings 'misc';
68 die $e if $e; # rethrow
69}
70
56ffe19d 71sub DEMOLISHALL {
72 my $self = shift;
73 $self->${\(($DEMOLISH_MAKER ||= do {
74 require Method::Generate::DemolishAll;
75 Method::Generate::DemolishAll->new
76 })->generate_method(ref($self)))}(@_);
77}
c2cc003f 78
6c74d087 79sub does {
80 require Role::Tiny;
81 { no warnings 'redefine'; *does = \&Role::Tiny::does_role }
82 goto &Role::Tiny::does_role;
83}
84
851;