当 Moose 中的基础属性发生更改时重建延迟构建的属性
我有一个带有 lazy_build
属性的 Moose 类。该属性的值是另一个(非惰性)属性的函数。
假设有人用所需属性的值 42 来实例化该类。然后他们请求了lazy属性,这个属性是按照42的函数计算出来的。然后,他们居然还好意思去改变第一个属性!
惰性属性已经构建完毕,因此构建器不会再次被调用,并且惰性属性现在已经过时了。
我现在有一个解决方案,在所需属性上维护一个“脏”标志,并且惰性属性上的访问器检查脏标志并在需要时重建它。
然而,这似乎需要大量工作。有没有办法在 Moose 中处理这个问题,例如使用特征?
I've got a Moose class with a lazy_build
attribute. The value of that attribute is a function of another (non-lazy) attribute.
Suppose somebody instantiates the class with a value of 42 for the required attribute. Then they request the lazy attribute, which is calculated as a function of 42. Then, they have the nerve to change the first attribute!
The lazy one has already been built, so the builder will not get called again, and the lazy attribute is now out-of-date.
I have a solution now where I maintain a "dirty" flag on the required attribute, and an accessor on the lazy one checks the dirty flag and rebuilds it if needed.
However, this seems like a lot of work. Is there a way to handle this within Moose, e.g. using traits?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的典型解决方案:
即当attr1更新时,attr2被清除,并在下次访问时重建。当您使用
lazy_build
时,clear_attr2
是免费的。只要您使用访问器方法,就不需要“脏”标志。这是一种常见的模式 - 处理“派生”属性的某种特征会很好。
My typical solution:
i.e. when attr1 is updated, attr2 is cleared and will be rebuilt when it is next accessed.
clear_attr2
comes for free when you uselazy_build
. As long as you use the accessor methods, you don't need a 'dirty' flag.This is a common pattern - some kind of trait to handle 'derived' attributes would be nice.