Search code examples
perlmoosemoo

In Moose, if a role defines an attribute with a default, how do I change that default in my consuming class?


My Moose class consumes a role which I'm not allowed to change. That role defines an attribute with a default. I need my class to have that attribute, but with a different default.

Is that possible?

All I could come up with is surrounding the "new" method with some of my own code, as follows:

around new => sub {
    my ($orig, $self) = (shift, shift);
    return $self->$orig(@_, the_attribute => $new_value);
}

But I'm not sure if surrounding new is valid, and was also hoping for something more elegant.


Solution

  • A better, simpler way is to write this in your class:

    has '+the_attribute' => (
        default => sub{1},
    }
    

    has with a + lets you override just a specific property of an attribute.

    Much simpler than surrounding BUILDARGS.