0

I have the following code duplicated several times as I have several classes that follow the same pattern

use MooseX::Types -declare [ qw( Item ) ];jj
my $itc = $prefix . 'Item';
class_type Item, { class => $itc };
coerce Item, from HashRef, via { load_class( $itc )->new( $_ ) };

is there an easy way for me to deduplicate the code that creates the class_type and coercion? This is not a problem understanding MooseX::Types but a problem of a large amount of duplicated code. Here is a link to that code in its current state. It's turned into a bit of a mess, and isn't something I'm proud of.

xenoterracide
  • 16,274
  • 24
  • 118
  • 243

1 Answers1

0

First your example code is not syntactically correct.

Second I think that your question (if I understood it correctly) is directly answered in MooseX::Types documentation. Just follow the example given there:

package MyTypes;

my @types = qw/Item1 Item2/;

use MooseX::Types -declare => [ @types];

use MooseX::Types::Moose qw/Int HashRef/;
use Moose::Util::TypeConstraints;

use URI;

foreach my $type (@types) {

  class_type $type, { class => 'URI' };
  coerce $type, from 'Str', via { URI->new( $_ ) };
}

1;

package Foo;

use Moose;

has test => (is => 'rw', isa => 'Item1', coerce => 1);

1;

package main;

use v5.10;
use strict;
use warnings;


 my $t = Foo->new(test => 'http://test.com');
 say $t->test;
jira
  • 3,890
  • 3
  • 22
  • 32
  • fixed the syntax error, but no, I know how to make them, the problem is I have like 20 of them that are the exact same sequence... I'm trying to reduce line count – xenoterracide Oct 05 '12 at 18:34
  • for some reason I get this `WARNING: String found where Type expected (did you use a => instead of a , ?) at /home/libdevel/Business-CyberSource/lib/MooseX/Types/CyberSource.pm line 173.` When I attempt to add it into my type library, I'm not sure why it no longer seems to export the names into the local namespace – xenoterracide Oct 08 '12 at 10:38
  • after further testing I have determined this only works if you aren't using the exporter/importer (meaning in a single file) if you actually have to do `use MyTypes qw( Item1 )` it doesn't work. Because MooseX::Types isn't able to export `Item1`. This is relying on "namespace bleed" because main can see what's in MyTypes – xenoterracide Oct 08 '12 at 11:20