Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Moose "unions" and inheritance

by tobyink (Canon)
on Nov 30, 2012 at 12:30 UTC ( [id://1006468]=note: print w/replies, xml ) Need Help??


in reply to Moose "unions" and inheritance

Further to my previous answer, here's another way to do it. It pushes all the ugly out to an attribute trait.

use v5.14; use strict; use warnings; # The ugly lives in this package package MooseX::UnionInheritedTypeConstraint { use Moose::Role; use Moose::Util::TypeConstraints -all; use namespace::clean -except => ['meta']; around new => sub { my ($orig, $class, $name, %options) = @_; if (my $new = $options{isa}) { my $existing = $options{associated_class} -> find_attribute_by_name($name) -> type_constraint; if ($existing) { $new = Moose::Util::TypeConstraints::find_or_parse_typ +e_constraint($new) unless ref $new; $options{isa} = union([$existing, $new]); } } $class->_process_isa_option($name, \%options); # maybe need to process coerce too?? return $class->$orig($name, %options); }; } # No ugly below! package KeyAtom { use Moose; has data => ( is => 'rw', isa => 'Str | RegexpRef', ); } package ValAtom { use Moose; extends 'KeyAtom'; has '+data' => ( traits => [ 'MooseX::UnionInheritedTypeConstraint' ], isa => 'ArrayRef | 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!

You might notice that I've managed to avoid the dependency on MooseX::Types here; though the trait should work equally well if you're using MooseX::Types.

PS: You can actually see the code that Moose uses to check type constraints. This is sometimes handy...

my $tc = ValAtom->meta->get_attribute('data')->type_constraint; say $tc->_inline_check('$value') if $tc->can_be_inlined;
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1006468]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-04-18 17:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found