Fix the order that BUILD methods are called in (thanks Robert Boone)
[gitmo/Mouse.git] / lib / Mouse / Object.pm
index 4af0f39..265787a 100644 (file)
@@ -13,10 +13,11 @@ sub new {
     my $instance = bless {}, $class;
 
     for my $attribute (values %{ $class->meta->get_attribute_map }) {
-        my $key = $attribute->init_arg;
+        my $from = $attribute->init_arg;
+        my $key  = $attribute->name;
         my $default;
 
-        if (!exists($args{$key})) {
+        if (!exists($args{$from})) {
             if ($attribute->has_default || $attribute->has_builder) {
                 unless ($attribute->is_lazy) {
                     my $default = $attribute->default;
@@ -33,7 +34,7 @@ sub new {
                     $instance->{$key} = $value;
 
                     weaken($instance->{$key})
-                        if $attribute->weak_ref;
+                        if ref($instance->{$key}) && $attribute->is_weak_ref;
                 }
             }
             else {
@@ -43,17 +44,17 @@ sub new {
             }
         }
 
-        if (exists($args{$key})) {
-            $attribute->verify_type_constraint($args{$key})
+        if (exists($args{$from})) {
+            $attribute->verify_type_constraint($args{$from})
                 if $attribute->has_type_constraint;
 
-            $instance->{$key} = $args{$key};
+            $instance->{$key} = $args{$from};
 
             weaken($instance->{$key})
-                if $attribute->weak_ref;
+                if ref($instance->{$key}) && $attribute->is_weak_ref;
 
             if ($attribute->has_trigger) {
-                $attribute->trigger->($instance, $args{$key}, $attribute);
+                $attribute->trigger->($instance, $args{$from}, $attribute);
             }
         }
     }
@@ -73,7 +74,7 @@ sub BUILDALL {
 
     no strict 'refs';
 
-    for my $class ($self->meta->linearized_isa) {
+    for my $class (reverse $self->meta->linearized_isa) {
         my $code = *{ $class . '::BUILD' }{CODE}
             or next;
         $code->($self, @_);