move to early generation of DESTROY/DEMOLISHALL where possible and hope like hell...
[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;
31eec6e8 12 unless (exists $NO_DEMOLISH{$class}) {
13 unless ($NO_DEMOLISH{$class} = !$class->can('DEMOLISH')) {
14 ($DEMOLISH_MAKER ||= do {
15 { local $@; require Method::Generate::DemolishAll; }
16 Method::Generate::DemolishAll->new
17 })->generate_method($class);
18 }
19 }
098a367b 20 $NO_BUILD{$class} and
21 return bless({ ref($_[0]) eq 'HASH' ? %{$_[0]} : @_ }, $class);
22 $NO_BUILD{$class} = !$class->can('BUILD') unless exists $NO_BUILD{$class};
23 $NO_BUILD{$class}
24 ? bless({ ref($_[0]) eq 'HASH' ? %{$_[0]} : @_ }, $class)
077bd026 25 : do {
5d349892 26 my $proto = ref($_[0]) eq 'HASH' ? $_[0] : { @_ };
27 bless({ %$proto }, $class)->BUILDALL($proto);
077bd026 28 };
098a367b 29}
30
0123201b 31# Inlined into Method::Generate::Constructor::_generate_args() - keep in sync
a17be455 32sub BUILDARGS {
33 my $class = shift;
34 if ( scalar @_ == 1 ) {
35 unless ( defined $_[0] && ref $_[0] eq 'HASH' ) {
36 die "Single parameters to new() must be a HASH ref"
b512e801 37 ." data => ". $_[0] ."\n";
a17be455 38 }
39 return { %{ $_[0] } };
40 }
41 elsif ( @_ % 2 ) {
bbed1e70 42 die "The new() method for $class expects a hash reference or a key/value list."
b512e801 43 . " You passed an odd number of arguments\n";
a17be455 44 }
45 else {
46 return {@_};
47 }
48}
49
098a367b 50sub BUILDALL {
51 my $self = shift;
52 $self->${\(($BUILD_MAKER ||= do {
59812c87 53 { local $@; require Method::Generate::BuildAll; }
098a367b 54 Method::Generate::BuildAll->new
55 })->generate_method(ref($self)))}(@_);
6c74d087 56}
57
59812c87 58sub DEMOLISHALL {
59 my $self = shift;
60 $self->${\(($DEMOLISH_MAKER ||= do {
61 { local $@; require Method::Generate::DemolishAll; }
62 Method::Generate::DemolishAll->new
63 })->generate_method(ref($self)))}(@_);
64}
65
6c74d087 66sub does {
59812c87 67 { local $@; require Role::Tiny; }
6c74d087 68 { no warnings 'redefine'; *does = \&Role::Tiny::does_role }
69 goto &Role::Tiny::does_role;
70}
71
721;