| 1 | package MooseX::Alien; | ||
| 2 | ## Copyright (C) Graham Barr | ||
| 3 | ## vim: ts=8:sw=2:expandtab:shiftround | ||
| 4 | |||
| 5 | use strict; | ||
| 6 | use warnings; | ||
| 7 | |||
| 8 | our $VERSION = '1.01'; | ||
| 9 | |||
| 10 | # Cannot import from Moose::Role as that would call init_meta, but without metaclass | ||
| 11 | use Moose::Role (); | ||
| 12 | |||
| 13 | Moose::Role->init_meta( | ||
| 14 | for_class => 'MooseX::Alien', | ||
| 15 | metaclass => 'MooseX::Alien::Meta' | ||
| 16 | ); | ||
| 17 | |||
| 18 | |||
| 19 | ($Moose::VERSION >= 0.90 ? __PACKAGE__->meta : __PACKAGE__)->Moose::Role::around( | ||
| 20 | 'new' => sub { | ||
| 21 | my $orig = shift; | ||
| 22 | my $obj = $orig->(@_); | ||
| 23 | my $class = shift; | ||
| 24 | my $params = $class->BUILDARGS(@_); | ||
| 25 | $params->{__INSTANCE__} = $obj; | ||
| 26 | my $self = $class->meta->new_object($params); | ||
| 27 | delete $params->{__INSTANCE__}; | ||
| 28 | $self->BUILDALL($params); | ||
| 29 | return $self; | ||
| 30 | } | ||
| 31 | ); | ||
| 32 | |||
| 33 | package MooseX::Alien::Meta; | ||
| 34 | use base qw(Moose::Meta::Role); | ||
| 35 | |||
| 36 | sub apply { | ||
| 37 | my $self = shift; | ||
| 38 | my $other = shift; | ||
| 39 | my @supers = $other->superclasses; | ||
| 40 | |||
| 41 | my $moose_supers = grep { $_->isa('Moose::Object') } @supers; | ||
| 42 | if (@supers == $moose_supers) { | ||
| 43 | Moose->throw_error("Must call extends with alien class before applying MooseX::Alien role"); | ||
| 44 | } | ||
| 45 | |||
| 46 | $other->superclasses(@supers, 'Moose::Object') | ||
| 47 | unless $moose_supers; | ||
| 48 | |||
| 49 | # Traverse superclasses, if first that defines a new method | ||
| 50 | # is not a Moose::Object, then we need to wrap it | ||
| 51 | foreach my $super (@supers) { | ||
| 52 | return if $super->isa('Moose::Object'); | ||
| 53 | if ($super->can('new')) { | ||
| 54 | $self->SUPER::apply($other, @_); | ||
| 55 | } | ||
| 56 | } | ||
| 57 | } | ||
| 58 | |||
| 59 | 1; | ||
| 60 | |||
| 61 | __END__ |