如何在 Moose 对象中设置一堆属性构建器?
我有以下五个 Moose 属性:
has ['summary_file', 'html_file', 'url1', 'url2', 'txt_file'] => (
is => 'rw',
isa => 'Str',
required => 0,
lazy => 1,
default => sub { confess "Attribute not set"; },
);
我想:
- 让每个属性都使用自己的构建器(例如 set
'summary_file'
使用_build_summary_file
等) - 设为默认值
承认
子状态调用了哪个(未初始化)属性(例如“属性'summary_file'未设置”
)。
我可以通过编写五个单独的 has
来完成上述任务,但也许有更紧凑的方法?
I have the following five Moose attributes:
has ['summary_file', 'html_file', 'url1', 'url2', 'txt_file'] => (
is => 'rw',
isa => 'Str',
required => 0,
lazy => 1,
default => sub { confess "Attribute not set"; },
);
I would like to:
- Make each of them use its own builder (e.g. set
'summary_file'
use_build_summary_file
, etc.) - Make the default
confess
sub state which (uninitialized) attribute was called (e.g."Attribute 'summary_file' not set"
).
I can accomplish the above by writing five separate has
's, but perhaps there's a more compact way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以执行类似以下操作(下面的“不起作用”评论后的新工作示例):
请注意,您不能同时指定
default
和builder
.@Oesor 在评论中指出了一些我忘记的事情:
You could do something the like following (new working example after your "does not work" comment below):
Note that you cannot specify both a
default
and abuilder
.@Oesor points out in a comment something I forgot:
如果您正在寻找一个在未设置值时在访问时引发异常的属性,请查看 MooseX::LazyRequire。
如果您正在寻找一个构建器在调用时抛出警告,请将该语句包含在构建器方法中...或者包装访问器/读取器方法来执行此操作。 (例如“
before 'attribute_name' => sub { ...complain... };
”)如果您正在寻找一种使用相同命名约定为属性指定构建器方法的方法lazy_build 确实如此,请参阅 MooseX::AttributeShortcuts (支持 '
builder => 1
' 为 'builder => "_build_${attribute_name}"
')。If you're looking for an attribute to throw an exception on access when it does not have a value set, look at MooseX::LazyRequire.
If you're looking for a builder to throw an warning if it's called, include that statement in the builder method... OR wrap the accessor/reader method to do that. (e.g. "
before 'attribute_name' => sub { ...complain... };
")If you're looking for an way to specify builder methods to an attribute using the same naming convention lazy_build does, see MooseX::AttributeShortcuts (supporting '
builder => 1
' as 'builder => "_build_${attribute_name}"
').