NAME

MooX::Enumeration - shortcuts for working with enum attributes in Moo

SYNOPSIS

Given this class:

   package MyApp::Result {
      use Moo;
      use Types::Standard qw(Enum);
      has status => (
         is        => "rw",
         isa       => Enum[qw/ pass fail /],
      );
   }

It's quite common to do this kind of thing:

   if ( $result->status eq "pass" ) { ... }

But if you're throwing strings around, it can be quite easy to mistype them:

   if ( $result->status eq "apss" ) { ... }

And the comparison silently fails. Instead, let's define the class like this:

   package MyApp::Result {
      use Moo;
      use MooX::Enumeration;
      use Types::Standard qw(Enum);
      has status => (
         is        => "rw",
         isa       => Enum[qw/ pass fail /],
         handles   => [qw/ is_pass is_fail /],
      );
   }

So you can use the class like this:

   if ( $result->is_pass ) { ... }

Yay!

DESCRIPTION

This is a Moo implementation of MooseX::Enumeration. All the features from the Moose version should work here.

Passing traits => ["Enumeration"] to has is not needed with MooX::Enumeration. This module's magic is automatically applied to all attributes with a Type::Tiny::Enum type constraint.

Simple example:

   package MyClass {
      use Moo;
      use MooX::Enumeration;
      
      has xyz => (is => "ro", enum => [qw/foo bar baz/], handles => 1);
   }

MyClass->new(xyz => "quux") will throw an error.

Objects of the class will have $object->is_foo, $object->is_bar, and $object->is_baz methods.

If you use handles => 2, then you get $object->xyz_is_foo, etc methods.

For more details of method delegation, see MooseX::Enumeration.

Use in roles

Since version 0.009, this will work in roles too, but with a caveat.

The coderef to be installed into the class is built when defining the role, and not when composing the role with the class, so the coderef has no knowledge of the class. In particular, it doesn't know anything about what kind of reference the blessed object will be (hashref, arrayref, etc), so just assumes that it will be a hashref, and that the hash key used for the attribute will match the attribute name. Unless you're using non-hashref objects or you're doing unusual things with Moo internals, these assumptions will usually be safe.

BUGS

Please report any bugs to http://rt.cpan.org/Dist/Display.html?Queue=MooX-Enumeration.

SEE ALSO

MooseX::Enumeration.

Type::Tiny::Enum.

Moo.

AUTHOR

Toby Inkster <tobyink@cpan.org>.

COPYRIGHT AND LICENCE

This software is copyright (c) 2018 by Toby Inkster.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.

DISCLAIMER OF WARRANTIES

THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.