Search code examples
perlmoose

How can I modify a Moose attribute handle?


Following phaylon's answer to "How can I flexibly add data to Moose objects?", suppose I have the following Moose attribute:

has custom_fields => (
    traits     => [qw( Hash )],
    isa        => 'HashRef',
    builder    => '_build_custom_fields',
    handles    => {
        custom_field         => 'accessor',
        has_custom_field     => 'exists',
        custom_fields        => 'keys',
        has_custom_fields    => 'count',
        delete_custom_field  => 'delete',
    },
);

sub _build_custom_fields { {} }

Now, suppose I'd like to croak if trying to read (but not write) to a non-existing custom field. I was suggested by phaylon to wrap custom_field with an around modifier. I have experimented with around modifiers following the various examples in Moose docs, but couldn't figure how to modify a handle (rather than just an object method).

Alternatively, is there another way to implement this croak-if-try-to-read-nonexisting-key?


Solution

  • They're still just methods generated by Moose. You can just do:

    around 'custom_field' => sub {
        my $orig  = shift;
        my $self  = shift;
        my $field = shift;
    
        confess "No $field" unless @_ or $self->has_custom_field($field);
    
        $self->$orig($field, @_);
    };
    

    (croak is not very useful in method modifiers at the moment. It will just point you at internal Moose code.)

    In fact, you don't need to use around for this. Using before is simpler:

    before 'custom_field' => sub {
        my $self  = shift;
        my $field = shift;
    
        confess "No $field" unless @_ or $self->has_custom_field($field);
    };