MooseX...rtcuts(3pm)

πŸ“¦
version 0.037 Β· 4 versions
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

🌸 MooseX::AttributeShortcuts πŸ’…

okay bestie, welcome to MooseX...rtcuts(3pm) β€” yes that's the manual name, it's giving abbreviation energy, we move. This is User Contributed Perl Documentation and it's about to change your whole attribute game, no cap.


✨ NAME ✨

MooseX::AttributeShortcuts β€” Shorthand for common attribute options. That's it. That's the vibe. Shortcuts, fr fr. πŸŽ€


🌈 VERSION 🌈

This document describes version 0.037 of MooseX::AttributeShortcuts β€” released November 20, 2017 as part of MooseX-AttributeShortcuts. Iconic release date behavior. πŸ¦‹


⭐ SYNOPSIS ⭐

package Some::Class;

use Moose;
use MooseX::AttributeShortcuts;

# same as:
#   is => 'ro', lazy => 1, builder => '_build_foo'
has foo => (is => 'lazy');

# same as: is => 'ro', writer => '_set_foo'
has foo => (is => 'rwp');

# same as: is => 'ro', builder => '_build_bar'
has bar => (is => 'ro', builder => 1);

# same as: is => 'ro', clearer => 'clear_bar'
has bar => (is => 'ro', clearer => 1);

# same as: is => 'ro', predicate => 'has_bar'
has bar => (is => 'ro', predicate => 1);

# works as you'd expect for "private": predicate => '_has_bar'
has _bar => (is => 'ro', predicate => 1);

# extending? Use the "Shortcuts" trait alias
extends 'Some::OtherClass';
has '+bar' => (traits => [Shortcuts], builder => 1, ...);

like. look at that. so much less typing. your wrists are thriving. πŸ’–


πŸ‘‘ DESCRIPTION πŸ‘‘

Bestie, real talk: do you ever find yourself repeatedly specifying writers and builders because there's literally no good shortcut for them? 😭 Sometimes you want an attribute to have a read-only public interface but a private writer, and the way that there's no shorthand for that is genuinely tragic. And wouldn't it just be easier to say builder => 1 and have the attribute construct the canonical _build_$name builder name for you? Yes. Obviously yes.

This package causes an attribute trait to be applied to all attributes defined to the using class. This trait extends the attribute option processing to handle all the variations above. And important, bestie: all attribute options as described in Moose or Class::MOP::Attribute remain usable, just as when this trait is not applied. Nothing gets taken away. We only add. periodt. πŸ’…

πŸ•°οΈ Some Notes On History πŸ•°οΈ

Moose has long had a lazy_build attribute option. It was once considered a best practice, but that has, ah, changed. This trait began as a desire to still leverage bits of lazy_build (and a tacit acknowledgment that fat-finger bugs rank among the most embarrassing, right up there with "the TV was unplugged the entire time"). πŸ™ˆ relatable honestly.

This author does not recommend you use lazy_build, unless you know exactly what you're doing (probably) and that it's a good idea (probably not). read that again, bestie.

Nonetheless, this lazy_build option is why we set certain options the way we do below; while lazy_build in its entirety is not optimal, it had the right idea: regular, predictable accessor names for regular, predictable attribute options. main character energy for consistency, honestly.

As an example, just looking at the below it doesn't seem logical that:

has _foo => (is => 'ro', clearer => 1);

...becomes:

has _foo => (is => 'ro', clearer => '_clear_foo');

After reading the lazy_build attribute option, however, we see that the choice had already been made for us. the lore is deep. 🫢


πŸ’œ USAGE πŸ’œ

This package automatically applies an attribute metaclass trait. Simply using this package causes the trait to be applied by default to your attribute's metaclasses. no extra steps. it's giving effortless. ✨


πŸ¦‹ EXTENDING A CLASS πŸ¦‹

If you're extending a class and trying to extend its attributes as well, you'll find out that the trait is only applied to attributes defined locally in the class. sneaky little gotcha, we know. 😀

This package exports a trait shortcut function Shortcuts that will help you apply this to the extended attribute:

has '+something' => (traits => [Shortcuts], ...);

slay. that's the fix. πŸŽ€


🌸 NEW ATTRIBUTE OPTIONS 🌸

Unless specified here, all options defined by Moose::Meta::Attribute and Class::MOP::Attribute remain unchanged. untouched. pristine. we respect the classics. πŸ’–

Want to see additional options? Ask, or better yet, fork on GitHub and send a pull request. If the shortcuts you're asking for already exist in Moo or Mouse or elsewhere, please note that as it will carry significant weight. πŸ‘€ (iykyk β€” receipts matter.)

For the following, $name should be read as the attribute name; and the various prefixes should be read using the defaults.


πŸ’… is => 'rwp'

Specifying is => 'rwp' will cause the following options to be set:

is     => 'ro'
writer => "_set_$name"

rwp can be read as "read + write private". read-only to the world, private writer for you. it's giving mysterious. 😌


πŸ’… is => 'lazy'

Specifying is => 'lazy' will cause the following options to be set:

is       => 'ro'
builder  => "_build_$name"
lazy     => 1
NOTE: Since 0.009 we no longer set init_arg => undef if no init_arg is explicitly provided. This is a change made in parallel with Moo, based on a large number of people surprised that lazy also made one's init_def undefined. 😭

πŸ’… is => 'lazy', default => ...

Specifying is => 'lazy' and a default will cause the following options to be set:

is       => 'ro'
lazy     => 1
default  => ... # as provided

That is, if you specify is => 'lazy' and also provide a default, then we won't try to set a builder, as well. one or the other, bestie. we're not gonna fight about it. ✨


πŸ’… builder => 1

Specifying builder => 1 will cause the following options to be set:

builder => "_build_$name"

πŸ’… builder => sub { ... }

Passing a coderef to builder will cause that coderef to be installed in the class this attribute is associated with the name you'd expect, and builder => 1 to be set. obsessed with the convenience, ngl.

e.g., in your class (or role),

has foo => (is => 'ro', builder => sub { 'bar!' });

...is effectively the same as...

has foo => (is => 'ro', builder => '_build_foo');
sub _build_foo { 'bar!' }

The behaviour of this option in roles changed in 0.030, and the builder methods will be installed in the role itself. This means you can alias/exclude/etc builder methods in roles, just as you can with any other method. glow up behavior. πŸ‘‘


πŸ’… clearer => 1

Specifying clearer => 1 will cause the following options to be set:

clearer => "clear_$name"

or, if your attribute name begins with an underscore:

clearer => "_clear$name"

(that is, an attribute named _foo would get _clear_foo). the underscore handling is the detail that eats, honestly. πŸ”₯


πŸ’… predicate => 1

Specifying predicate => 1 will cause the following options to be set:

predicate => "has_$name"

or, if your attribute name begins with an underscore:

predicate => "_has$name"

(that is, an attribute named _foo would get _has_foo). same energy, different prefix. πŸ’–


πŸ’… init_arg => 1 / -1

This is a somewhat esoteric shortcut; you probably don't want to use this (or even read this section). 🫣 but we're putting it here anyway because every detail stays, bestie. that's the rule.

Specifying init_arg => 1 will cause the following options to be set:

# attribute: "name"
init_arg => 'name'

# or, attribute: "_name"
init_arg => '_name'

...while init_arg => -1 will cause the following options to be set:

# attribute: "name"
init_arg => '_name'

# or, attribute: "_name"
init_arg => 'name'

it flips them. that's it. that's the whole thing. 🀯


πŸ’… trigger => 1

Specifying trigger => 1 will cause the attribute to be created with a trigger that calls a named method in the class with the options passed to the trigger. By default, the method name the trigger calls is the name of the attribute prefixed with _trigger_.

e.g., for an attribute named foo this would be equivalent to:

trigger => sub { shift->_trigger_foo(@_) }

For an attribute named _foo:

trigger => sub { shift->_trigger__foo(@_) }

This naming scheme, in which the trigger is always private, is the same as the builder naming scheme (just with a different prefix). consistency is the moment. ✨


πŸ’… handles => { foo => sub { ... }, ... }

Creating a delegation with a coderef will now create a new, "custom accessor" for the attribute. These coderefs will be installed and called as methods on the associated class (just as readers, writers, and other accessors are), and will have the attribute metaclass available in $_. Anything the accessor is called with it will have access to in @_, just as you'd expect of a method. 😌

e.g., the following example creates an attribute named bar with a standard reader accessor named bar and two custom accessors named foo and foo_too.

has bar => (

    is      => 'ro',
    isa     => 'Int',
    handles => {

        foo => sub {
            my $self = shift @_;

            return $_->get_value($self) + 1;
        },

        foo_too => sub {
            my $self = shift @_;

            return $self->bar + 1;
        },

        # ...as you'd expect.
        bar => 'bar',
    },
);

...and later,

Note that in this example both foo() and foo_too() do effectively the same thing: return the attribute's current value plus 1. However, foo() accesses the attribute value directly through the metaclass, the pros and cons of which this author leaves as an exercise for the reader to determine. πŸ™ˆ

You may choose to use the installed accessors to get at the attribute's value, or use the direct metaclass access, your choice. both are valid, bestie. live your truth. πŸ’…

🌈 ANONYMOUS SUBTYPING AND COERCION 🌈

"Abusus non tollit usum."

Okay so real talk, bestie: whenever you drop constraint or coerce options in a way that wakes up the Shortcuts trait (aka this one, hiii πŸ’–), we are out here creating brand-new anonymous subtypes. And yes, using both constraint and coerce at the same time? Fully supported. Slay.

This whole thing is meant to help you make one-off type constraints and coercions. But lowkey important: you cannot deliberately reuse the subtypes we create. If you catch yourself using the same isa / constraint / coerce option triplet in more than one place, bestie, it's giving reusable-type energy. You should really think about making a type you can reuse. MooseX::Types has the facilities to do this easily, or you can even do a simple constant definition at the package level with an anonymous type stashed away for local use. Periodt.


isa => sub { ... }

has foo => (
    is  => 'rw',
    # $_ == $_[0] == the value to be validated
    isa => sub { die unless $_[0] == 1 },
);

# passes constraint
$thing->foo(1);

# fails constraint
$thing->foo(5);

Hand it a coderef and boom πŸ’₯ you get a type constraint for the attribute. If the coderef dies, the constraint fails. If it doesn't die, it passes. Simple as that.

Astute besties will clock that this is literally the same way Moo constraints work. We use MooseX::Meta::TypeConstraint::Mooish to implement the constraint. No cap.


isa_instance_of => ...

Give it a package name and it creates an isa type constraint that requires the attribute's value to be an instance of the class you named β€” or a descendant class, we're not picky. So this:

has foo => (is => 'ro', isa_instance_of => 'SomeThing');

...is effectively the same as:

use Moose::TypeConstraints 'class_type';
has foo => (
    is  => 'ro',
    isa => class_type('SomeThing'),
);

...but a touch less awkward, fr fr.


isa => ..., constraint => sub { ... }

Put a coderef in the constraint option and you get a new subtype constraint. The parent type is whatever you put in isa, and the constraint is the coderef you supplied. Iconic.

For example, only integers greater than 10 will pass this attribute's type constraint:

# value must be an integer greater than 10 to pass the constraint
has thinger => (
    isa        => 'Int',
    constraint => sub { $_ > 10 },
    # ...
);

Important: if you supply a constraint, you must also provide an isa. Don't skip it.


isa => ..., constraint => sub { ... }, coerce => 1

Give it a constraint and ask for coercion and it will Just Work. That means any coercions that the isa type already has will still work. It's giving teamwork.

For example, let's say that you're using the File type constraint from MooseX::Types::Path::Class, and you want an additional constraint that the file must exist:

has thinger => (
    is         => 'ro',
    isa        => File,
    constraint => sub { !! $_->stat },
    coerce     => 1,
);

thinger will correctly coerce the string "/etc/passwd" to a Path::Class:File, and will only accept the coerced result as a value if the file exists. Vibe check passed only when the file is real.


coerce => [ Type => sub { ...coerce... }, ... ]

Specifying the coerce option with a hashref will cause a new subtype to be created and used (just as with the constraint option, above), with the specified coercions added to the list. In the passed hashref, the keys are Moose types (well, strings resolvable to Moose types), and the values are coderefs that will coerce a given type to our type.

has bar => (
    is     => 'ro',
    isa    => 'Str',
    coerce => [
        Int    => sub { "$_"                       },
        Object => sub { 'An instance of ' . ref $_ },
    ],
);

πŸ¦‹ INTERACTIONS WITH OTHER ATTRIBUTE TRAITS πŸ¦‹

Sometimes attribute traits interact in surprising ways. This trait is well behaved though, okay? But if you've discovered any interactions with other traits β€” good, bad, indifferent, whatever β€” please report this <https://github.com/RsrchBoy/moosex-attributeshortcuts/issues/new> so it can be worked around, fixed, or documented, as appropriate. We're listening πŸ‘‚

MooseX::SemiAffordanceAccessor

MooseX::SemiAffordanceAccessor changes how the is => 'rw' and accessor => ... attribute options work. If our trait detects that an attribute has had the MooseX::SemiAffordanceAccessor attribute trait applied, then we change our behaviour to conform to its expectations. We're flexible like that.

So here's the tea β˜•:

  • is => 'rwp' β€” This:
has  foo => (is => 'rwp');
has _bar => (is => 'rwp');

...is now effectively equivalent to:

has foo  => (is => 'ro', writer => '_set_foo');
has _bar => (is => 'ro', writer => '_set_bar')
  • -writer_prefix is ignored β€” ...as MooseX::SemiAffordanceAccessor has its own specific ideas as to how writers should look. Soz, it's not our call.

🌸 SEE ALSO 🌸

Please see those modules/websites for more information related to this module. Bestie, go read them, they're cute:

  • Moo
  • MooseX::Types
  • MooseX::SemiAffordanceAccessor

πŸŽ€ BUGS πŸŽ€

Please report any bugs or feature requests on the bugtracker website <https://github.com/RsrchBoy/moosex-attributeshortcuts/issues>. If you found a bug, bestie, don't suffer in silence.

When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. That way we can actually see the problem, periodt.


πŸ‘‘ AUTHOR πŸ‘‘

Chris Weyl <cweyl@alumni.drew.edu> β€” king behavior πŸ‘‘


πŸ’– CONTRIBUTORS πŸ’–

Shoutout to the contributors, they ate and left no crumbs:

  • David Steinbrunner <dsteinbrunner@pobox.com>
  • Graham Knop <haarg@haarg.org>
  • Karen Etheridge <ether@cpan.org>
  • Olaf Alders <olaf@wundersolutions.com>

This software is Copyright (c) 2017, 2015, 2014, 2013, 2012, 2011 by Chris Weyl. No cap.

This is free software, licensed under:

The GNU Lesser General Public License, Version 2.1, February 1999. Slay.


Okay bestie, that's the whole manual page for MooseX...rtcuts(3pm) β€” generated with perl v5.34.0 on 2022-06-15. Go forth and shortcut slay πŸ’…βœ¨