PrePAN

Sign in to PrePAN

MooX::TaggedAttributes Add tags w/ values to Moo attributes

Good

Synopsis

# Create a Role used to apply the attributes
package Tags;
use Moo::Role;
use MooX::TaggedAttributes -tags => [qw( t1 t2 )];

# Apply the role directly to a class
package C1;
use Tags;

has c1 => ( is => 'ro', t1 => 1 );

my $obj = C1->new;

# get the value of the tag t1, applied to attribute a1
$obj->_tags->{t1}{c1};

# Apply the tags to a role
package R1;
use Tag1;

has r1 => ( is => 'ro', t2 => 2 );

# Use that role in a class
package C2;
use R1;

has c2 => ( is => 'ro', t2 => sub { } );

# get the value of the tag t2, applied to attribute c2
C2->new->_tags->{t2}{c2};

Description

This module allows one to apply tags with values to attributes in Moo classes and Roles. Why?

Well, in my case I want to able to label attributes so that I can programatically find those with a particular label and operate on them.

For example, let's say that my class has attributes which are PDL objects (or piddles, as we call 'em), and I want to apply a transform just to those objects. Without tags, I'd have to know ahead of time which attributes were PDL objects, and which weren't. That might get complicated if I compose a bunch of roles (especially onto objects at run time).

With tagged attributes, I can do this:

package PDL::Tag;
use Moo::Role;
use MooX::TaggedAttributes -tags => 'piddle';

package MyClass;
use Moo;
use PDL::Tag;

has a => ( is => 'ro' );
has b => ( is => 'ro', piddle => 1 );

my $obj = MyClass->new( ... );

# search for attributes marked as piddles:
my @piddles = keys %{ $obj->_tags->{piddle} };

# and now do some Cool PDL stuff on 'em
$obj->$_->rotate(-1) for @piddles.

I could scan the attributes looking for a particular type, but tags are more elegant, and since they are arbitrary, can encode more information. The tag values are also arbitrary, so you can do anything you want with 'em.

Comments

I could use something like that, as a kind of MOP-lite.
Have you looked at https://metacpan.org/pod/MooX::ClassStash?
Please note that there are limitations in the current implementation which make it impossible to fully support a MOP.

Please sign up to post a review.