Recovering a lazy attribute when changing a base attribute in Moose

I have a Moose class with an attribute lazy_build. The value of this attribute is a function of another (nonslide) attribute.

Suppose someone creates an instance of a class with a value of 42 for the required attribute. Then they request a lazy attribute, which is calculated as a function of 42. Then they have a nerve to change the first attribute!

The lazy one has already been created, so the builder will not be called again, and the lazy attribute is now out of date.

I have a solution now that I support the dirty flag of the required attribute, and the accessory on the lazy one checks the dirty flag and restores it if necessary.

However, this seems like a lot of work. Is there a way to handle this in Moose, for example. using traits?

+5
source share
1 answer

My typical solution:

has 'attr1' => (
    ...
    trigger => \&clear_attr2, 
);

i.e. when attr1 is updated, attr2 is cleared and will be restored the next time it is accessed. clear_attr2provided free of charge when used lazy_build. As long as you use access methods, you don't need the dirty flag.

This is a common pattern - some feature would be nice to handle derived attributes.

+9
source

All Articles