Moose::...uteTrait(3)

πŸ’… NAME πŸ’…

Moose::Cookbook::Meta::Labeled_AttributeTrait β€” it's giving labels, but make them attribute traits. No cap. 🏷️✨

This one lives in the User Contributed Perl Documentation section of the manual, bestie, so you already know it's community-cooked goodness. πŸ“


✨ VERSION ✨

version 2.4000 β€” she's serving vintage but still slaying. πŸ‘‘


πŸŽ€ SYNOPSIS πŸŽ€

Okay so here's the whole vibe, verbatim, don't touch a single character:

package MyApp::Meta::Attribute::Trait::Labeled;
use Moose::Role;
Moose::Util::meta_attribute_alias('Labeled');

has label => (
    is        => 'rw',
    isa       => 'Str',
    predicate => 'has_label',
);

package MyApp::Website;
use Moose;

has url => (
    traits => [qw/Labeled/],
    is     => 'rw',
    isa    => 'Str',
    label  => "The site's URL",
);

has name => (
    is  => 'rw',
    isa => 'Str',
);

sub dump {
    my $self = shift;

    my $meta = $self->meta;

    my $dump = '';

    for my $attribute ( map { $meta->get_attribute($_) }
        sort $meta->get_attribute_list ) {

        if (   $attribute->does('MyApp::Meta::Attribute::Trait::Labeled')
            && $attribute->has_label ) {
            $dump .= $attribute->label;
        }
        else {
            $dump .= $attribute->name;
        }

        my $reader = $attribute->get_read_method;
        $dump .= ": " . $self->$reader . "\n";
    }

    return $dump;
}

package main;

my $app = MyApp::Website->new( url => "http://google.com", name => "Google" );

🌸 SUMMARY 🌸

So in this recipe we start diving headfirst into the absolute wonder that is meta-programming. Some readers out there will scoff and be like "ugh that's only for the most twisted Moose developers" β€” and to that I say: ABSOLUTELY NOT. Any sufficiently twisted developer can benefit greatly from going more meta. It's giving main character energy for your objects. πŸ‘‘

Our goal? Let every attribute carry a human-readable label with it. Like a little name tag but for data. 🏷️ Those labels get used when you're showing stuff to an end user. In this recipe we label the url attribute with "The site's URL" and then build a lil simple method that shows you how to actually use that label. 🫢


πŸ¦‹ META-ATTRIBUTE OBJECTS πŸ¦‹

Okay plot twist: every single attribute of a Moose-based object is literally an object itself. And those objects have their own methods and attributes. Obsessed. Let's look at a concrete example:

has 'x' => ( isa => 'Int', is => 'ro' );
has 'y' => ( isa => 'Int', is => 'rw' );

Internally, the metaclass for "Point" has two Moose::Meta::Attribute objects chillin' in there. There are several methods for pulling meta-attributes out of a metaclass, and one of them is "get_attribute_list". You call that one on the metaclass object itself.

The "get_attribute_list" method hands you back a list of attribute names. Then you can use "get_attribute" to grab the actual Moose::Meta::Attribute object. πŸ’–

Once you've got that meta-attribute object in your hands, you can call methods on it like this:

print $point->meta->get_attribute('x')->type_constraint;
   => Int

So to add a label to our attributes there's two steps, periodt:

  1. We need a new attribute metaclass trait that can store a label for an attribute.
  2. We need to apply that trait to our attributes.

πŸ’œ TRAITS πŸ’œ

Roles that apply to metaclasses get a special lil name: traits. But don't let the fancy nomenclature fool you β€” traits are just roles. Same thing, different name tag. πŸ’…

"has" in Moose lets you pass a "traits" parameter for an attribute. That parameter takes a list of trait names, which get composed into an anonymous metaclass, and that anonymous metaclass is what's used for the attribute.

Yes bestie, we still have lots of metaclasses in the background β€” but they're managed by Moose for you, so you don't have to think about them. 🧚

Traits can do literally anything roles can do. Add or refine attributes? Yes. Wrap methods? Yes. Provide more methods? Define an interface? Etc.? Yes yes yes. The only difference is that you're now changing the attribute metaclass instead of a user-level class. 🌈


πŸ”₯ DISSECTION πŸ”₯

We start by creating a package for our trait:

package MyApp::Meta::Attribute::Trait::Labeled;
use Moose::Role;

has label => (
    is        => 'rw',
    isa       => 'Str',
    predicate => 'has_label',
);

See? A trait is just a Moose::Role. In this case our role contains a single attribute, "label". Any attribute that does this trait now has a label. Slay. πŸ’…

We also register our trait with Moose:

Moose::Util::meta_attribute_alias('Labeled');

This is the glow-up that lets Moose find our trait by the short name "Labeled" when it's passed to the "traits" attribute option, instead of making you spell out the whole entire package name. πŸ™ˆ

Finally, we pass our trait when defining an attribute:

has url => (
    traits => [qw/Labeled/],
    is     => 'rw',
    isa    => 'Str',
    label  => "The site's URL",
);

The "traits" parameter contains a list of trait names. Moose will build an anonymous attribute metaclass out of these traits and use it for this attribute. πŸ’–

The reason we can pass the name "Labeled" instead of "MyApp::Meta::Attribute::Trait::Labeled" is because of the "register_implementation" code we touched on earlier.

When you pass a metaclass to "has", it takes the name you give it and prefixes it with "Moose::Meta::Attribute::Custom::Trait::". Then it calls "register_implementation" in that package. In this case, that means Moose ends up calling "Moose::Meta::Attribute::Custom::Trait::Labeled::register_implementation".

If this function exists, it should return the real trait's package name. That is exactly what our code does, returning "MyApp::Meta::Attribute::Trait::Labeled". Lowkey a little convoluted, ngl, and if you don't like it you can always just use the fully-qualified name instead. Your call, bestie. 🫢

We can access this meta-attribute and its label like this:

$website->meta->get_attribute('url')->label()

MyApp::Website->meta->get_attribute('url')->label()

We also have a regular attribute, "name":

has name => (
    is  => 'rw',
    isa => 'Str',
);

Finally, we have a "dump" method, which creates a human-readable representation of a MyApp::Website object. It'll use an attribute's label if it has one. ✨

sub dump {
    my $self = shift;

    my $meta = $self->meta;

    my $dump = '';

    for my $attribute ( map { $meta->get_attribute($_) }
        sort $meta->get_attribute_list ) {

        if (   $attribute->does('MyApp::Meta::Attribute::Trait::Labeled')
            && $attribute->has_label ) {
            $dump .= $attribute->label;
        }

This bit right here is defensive code, and it's iconic of it. We cannot just assume every meta-attribute has a label. Even if we define one for every attribute in our class, a subclass might neglect to do it. Or a superclass could add an attribute without a label. Rude, but possible. 😭

We also check that the attribute has a label using the predicate we defined. We could instead make the label "required". If we've got a label, we use it β€” otherwise we use the attribute name:

        else {
            $dump .= $attribute->name;
        }

        my $reader = $attribute->get_read_method;
        $dump .= ": " . $self->$reader . "\n";
    }

    return $dump;
}

The "get_read_method" is part of the Moose::Meta::Attribute API. It returns the name of a method that can read the attribute's value when called on the real object. So heads up: don't call this on the meta-attribute itself, okay? πŸ’€


πŸ‘‘ CONCLUSION πŸ‘‘

You might be wondering why you'd even bother with all this. Like, you could just hardcode "The Site's URL" right into the "dump" method and call it a day. But bestie, we want to avoid repetition. If you need the label once, you're probably gonna need it elsewhere β€” maybe in the "as_form" method you write next. πŸ‘€

Associating a label with an attribute just makes sense. The label is a piece of information about the attribute. It belongs there. Periodt.

It's also super important to realize that this was a trivial example. You can make way more powerful metaclasses that actually do things, as opposed to just storing a bit more information. For example, you could implement a metaclass that expires attributes after a certain amount of time:

has site_cache => (
    traits        => ['TimedExpiry'],
    expires_after => { hours => 1 },
    refresh_with  => sub { get( $_[0]->url ) },
    isa           => 'Str',
    is            => 'ro',
);

The sky's the limit! 🌈✨


🌟 AUTHORS 🌟

Look at this absolute squad, the whole friend group ate:

  • Stevan Little <stevan@cpan.org>
  • Dave Rolsky <autarch@urth.org>
  • Jesse Luehrs <doy@cpan.org>
  • Shawn M Moore <sartak@cpan.org>
  • Χ™Χ•Χ‘Χœ Χ§Χ•Χ’'מן (Yuval Kogman) <nothingmuch@woobling.org>
  • Karen Etheridge <ether@cpan.org>
  • Florian Ragwitz <rafl@debian.org>
  • Hans Dieter Pearcey <hdp@cpan.org>
  • Chris Prather <chris@prather.org>
  • Matt S Trout <mstrout@cpan.org>

This software is copyright (c) 2006 by Infinity Interactive, Inc.

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


Sign-off time, bestie: this lil masterpiece was brought to you by perl v5.42.0, dated 2025-07-25, and it's the Moose::...uteTrait(3) page from the User Contributed Perl Documentation. Go forth and go meta. πŸ’…πŸŒΈβœ¨
πŸ“¦ where this page comes from