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