gcbenison
gcbenison

Reputation: 11963

Moose class as an attribute type?

Is there a way to constrain the value of an attribute to be a class name that inherits from some particular class?

has thing_class => (
  ??? => Some::Base::Class,
);

Here a valid value for thing_class should be Some::Base::Class or a class derived from it. isa is not the right thing to use, because that would require that the attribute be an instantiated instance of Some::Base::Class.

Upvotes: 1

Views: 112

Answers (1)

ikegami
ikegami

Reputation: 385877

Type constraints are imposed by isa. Of course, you'll need to define a suitable type constraint first.

use Moose::Util::TypeConstraints;

subtype 'FooBarSubclassName',
   as 'Str',
   where { $_->isa('Foo::Bar') };

no Moose::Util::TypeConstraints;


has thing_class => (
  isa => 'FooBarSubclassName',
);

Upvotes: 3

Related Questions