http://www.perlmonks.org?node_id=1006450


in reply to Moose "unions" and inheritance

Firstly, when overriding an attribute definition in a child class, use:

has '+data' => ( ... );

This allows you to inherit attribute options from the parent class, so you don't need to redeclare, say, is => 'rw' (because the parent class has already declared that).

There isn't an especially elegant way of adding to the parent attribute's type constraints. This is the best I could do. I'm using MooseX::Types here because it makes things a little prettier. It's possible to do the same mucking around with Moose::Util::TypeConstraints but who's got the patience?!

use v5.14; use strict; use warnings; package KeyAtom { use Moose; use MooseX::Types::Moose -all; has data => ( is => 'rw', isa => Str | RegexpRef , ); } package ValAtom { use Moose; use MooseX::Types::Moose -all; extends 'KeyAtom'; sub _existing_constraint { my ($class, $attr) = @_; return $class->meta->find_attribute_by_name($attr)->type_const +raint; } has '+data' => ( isa => __PACKAGE__->_existing_constraint('data') | ArrayRe +f | HashRef, ); } ValAtom->new(data => 'Hello'); # Str ValAtom->new(data => qr{Hello}); # RegexpRef ValAtom->new(data => []); # ArrayRef ValAtom->new(data => {}); # HashRef ValAtom->new(data => \*STDOUT); # none of the above... crash!
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'