Commits

Toby Inkster committed 300cdf4

allow struct definitions to specify a package name for the resulting class

Comments (0)

Files changed (2)

lib/MooX/Struct.pm

 	my $counter = 0;
 	sub create_class
 	{
-		my $self  = shift;
-		my $klass = sprintf('%s::__ANON__::%04d', $self->base, ++$counter);
+		my ($self, $opts) = @_;
+		my $klass;
+		for my $o (@$opts) {
+			next unless $o->[0] eq '-class';
+			$klass = ref($o->[1]) eq 'ARRAY' ? join('::', @{$o->[1]}) : ${$o->[1]};
+			last;
+		}
+		$klass ||= sprintf('%s::__ANON__::%04d', $self->base, ++$counter);
 		Moo->_set_superclasses($klass, $self->base);
 		Moo->_maybe_reset_handlemoose($klass);
 		if ($self->trace)
 				grep { not ref $_ } @{ $Moo::Role::INFO{$role}{attributes} }
 			} @$val;
 		}
+		elsif ($name eq '-class')
+		{
+			# skip; already handled by 'create_class' method (hopefully)
+		}
 		else
 		{
 			confess("option '$name' unknown");
 			1 if $] < 5.014; # bizarre, but necessary!
 			if (ref $proto)  # inflate!
 			{
-				my $klass  = $self->create_class;
+				my $opts   = Data::OptList::mkopt($proto);
+				my $klass  = $self->create_class($opts);
 				my @fields = _uniq map {
 					$self->process_argument($klass, @$_)
-				} @{ Data::OptList::mkopt($proto) };
+				} @$opts;
 				$self->process_method($klass, FIELDS => sub { @fields });
 				$self->process_method($klass, TYPE   => sub { $subname }) if defined $subname;
 				$proto = $klass;
 use strict;
-use Test::More tests => 20;
+use Test::More tests => 24;
 use MooX::Struct
-	Agent        => [ name => undef ],
+	Agent        => [ name => undef, -class => \'Local::Test::Class1' ],
 	Organisation => [ -extends => ['Agent'], employees => undef, company_number => [is => 'rw']],
-	Person       => [ -extends => ['Agent'] ];
+	Person       => [ -extends => ['Agent'], -class => [qw/Local Test Class2/] ];
 
 my $alice = Person->new(name => 'Alice');
 my $bob   = Person->new(name => 'Bob');
 note sprintf("Person class:        %s", Person);
 note sprintf("Organisation class:  %s", Organisation);
 
+is(Agent, 'Local::Test::Class1');
+is(Person, 'Local::Test::Class2');
+isa_ok($alice, 'Local::Test::Class1');
+isa_ok($alice, 'Local::Test::Class2');
+
 is(
 	ref($alice),
 	ref($bob),