Moose:将参数注入构造中
我有一个附加了验证的文件名属性。现在,当在构造过程中未指定文件名时,我想从配置文件中读取它。
subtype 'filename'
=> as 'Str'
=> where { -r $_ }
=> message { "$_ is not a readable file" };
has 'students_file' => ( is => 'rw', isa => 'filename', default => '' );
has 'teachers_file' => ( is => 'rw', isa => 'filename', default => '' );
问题是 BUILD
似乎是在验证发生后运行的。 BUILDARGS
的所有示例似乎都处理构造对象的不同方式。
那么我应该在哪里读取配置并设置属性呢?
I have a filename attribute that has attached validation. Now when the filename isn't specified during construction I want to read it from a configuration file.
subtype 'filename'
=> as 'Str'
=> where { -r $_ }
=> message { "$_ is not a readable file" };
has 'students_file' => ( is => 'rw', isa => 'filename', default => '' );
has 'teachers_file' => ( is => 'rw', isa => 'filename', default => '' );
The issue is that BUILD
seems to be run after the validation occurs. All examples of BUILDARGS
seem to handle a different way of constructing the object.
So where should I read the configuration and set the attribute?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
提供从配置文件设置它们的
teachers_file
和students_file
builder
方法(或内联default
子函数)。仅当这些属性未作为构造函数的键提供时,构建器才会运行(除非您使用init_arg => undef
来阻止在构造函数中设置它们) 。如果您的配置是其自己的属性,并且具有读取配置文件的构建器,那么您在
config
和teachers_file
和students_file
之间存在排序问题代码>.您可以通过使teachers_file
和students_file
惰性属性来解决此问题,这确保它们不会尝试在 config 属性之前构造。但是,您可能希望确保在构造过程中尽早抛出“foo 不是可读文件”错误,而不是在第一次使用该属性时抛出。 解决这个问题。您可以通过添加确保在构造函数返回之前读取(并构造)这些属性一次来
Give
teachers_file
andstudents_file
builder
methods (or inlinedefault
subs) that set them from the config file. The builder will only run if those attributes aren't provided as keys to the constructor (unless you useinit_arg => undef
to prevent them from being set in the constructor).If your config is an attribute of its own, with a builder that reads the config file, then you have an ordering problem between
config
andteachers_file
andstudents_file
. You can resolve this by makingteachers_file
andstudents_file
lazy attributes, which ensures that they won't try to be constructed before the config attribute. However, you may want to make sure that the "foo is not a readable file" error is thrown as early as possible during construction, instead of the first time the attribute is used. You can work around that by addingwhich ensures that those attributes are read once (and constructed) before the constructor returns.