1 package LaTeX::TikZ::Meta::TypeConstraint::Autocoerce;
8 LaTeX::TikZ::Meta::TypeConstraint::Autocoerce - Type constraint metaclass that autoloads type coercions.
16 our $VERSION = '0.01';
22 extends any_moose('Meta::TypeConstraint');
29 has 'parent_name' => (
35 has 'user_constraint' => (
37 isa => 'Maybe[CodeRef]',
42 my ($orig, $class, %args) = @_;
44 unless (exists $args{mapper}) {
45 $args{mapper} = sub { join '::', $_[0]->parent_name, $_[1] };
48 my $parent = delete $args{parent};
49 $args{parent_name} = defined $parent
50 ? (blessed($parent) ? $parent->name : $parent)
53 $args{user_constraint} = $args{constraint};
55 if (any_moose() eq 'Moose') {
56 $args{coercion} = Moose::Meta::TypeCoercion->new;
59 my $parent_name = $args{parent_name};
60 $parent_name =~ s/::+/_/g;
63 $args{constraint} = Sub::Name::subname('_load' => sub {
67 $tc = $class->$orig(%args);
71 my ($tc, $thing) = @_;
73 # First, try a possible user defined constraint
74 my $user = $tc->user_constraint;
76 my $ok = $user->($thing);
80 # When ->check is called inside coerce, a return value of 0 means that
81 # coercion should take place, while 1 signifies that the value is already
84 my $class = blessed($thing);
85 return 0 unless $class;
86 return 1 if $class->isa($tc->parent_name);
88 my $mapper = $tc->mapper;
89 my $pm = $class = $tc->$mapper($class);
93 return 0 if $INC{$pm}; # already loaded
96 eval { require $pm; 1 };
101 around 'coerce' => sub {
102 my ($orig, $tc, $thing) = @_;
104 # The original coerce gets an hold onto the type coercions *before* calling
105 # the constraint. Thus, we have to force the loading before recalling into
106 # $orig. This is achieved by calling ->load.
107 return $thing if $tc->load($thing);
112 __PACKAGE__->meta->make_immutable(
113 inline_constructor => 0,
118 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
120 You can contact me by mail or on C<irc.perl.org> (vincent).
124 Please report any bugs or feature requests to C<bug-latex-tikz at rt.cpan.org>, or through the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=LaTeX-TikZ>.
125 I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
129 You can find documentation for this module with the perldoc command.
133 =head1 COPYRIGHT & LICENSE
135 Copyright 2010 Vincent Pit, all rights reserved.
137 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
141 1; # End of LaTeX::TikZ::Meta::TypeConstraint::Autocoerce