我开始意识到这是为初学者准备的:
I'm beginning to realize that this is for beginners:
package Bad; has 'arr' => ( is => 'rw', 'ArrayRef[Str]' ); package main; my $bad = Bad->new(arr => [ "foo", "bar" ]); print $bad->arr->[0], "\n";输入特征.不过,我对traits API 感到不知所措.我是不是误解了什么?我可以以某种方式获得这个 API 吗?:
Enter traits. I'm underwhelmed by the traits API, though. Have I misunderstood something? Can I get this API instead somehow? :
print $bad->arr->get(0), "\n";详情
查看 中的规范特征示例Moose::Meta::Attribute::Native::Trait::Array
package Stuff; use Moose; has 'options' => ( traits => ['Array'], is => 'ro', isa => 'ArrayRef[Str]', default => sub { [] }, handles => { all_options => 'elements', add_option => 'push', map_options => 'map', filter_options => 'grep', find_option => 'first', get_option => 'get', join_options => 'join', count_options => 'count', has_options => 'count', has_no_options => 'is_empty', sorted_options => 'sort', }, ); no Moose; 1;使用这样声明的对象,例如:
An object declared like that is used e.g.:
my $option = $stuff->get_option(1);对于我获得的一个数组属性,我真的不喜欢这样,并且必须在我的 Stuff 类中手动命名 11 个方法 - 一个用于可以对选项"执行的每一个操作.肯定会出现命名不一致的情况,而且很臃肿.
I really don't like that for one array attribute I get and have to manually name 11 methods in my Stuff class - one for every single operation that one can do to 'options'. Inconsistent naming is bound to happen and it is bloaty.
我如何(优雅地)获得如下 API:
How do I instead (elegantly) get an API like:
my $option = $stuff->options->get(1);所有方法来自 Moose::Meta::Attribute::Native::Trait::Array 是以类型安全的方式实现的吗?
Where all the methods from Moose::Meta::Attribute::Native::Trait::Array are implemented in a type-safe way?
然后对每个数组的所有操作都以完全相同的方式命名...
Then all the operations on every single Array are named in exactly the same way...
(我实际上使用的是鼠标,但大多数鼠标与麋鹿相同)
(I'm actually using Mouse, but most of Mouse is identical to Moose)
推荐答案我认为让您的 API 成为那种格式的最好方法是为选项创建一个新对象,并将方法直接委托给它.类似的东西:
I think that the best way to get your API into that format would be to create a new object for the options, and delegate the methods into it directly. Something like:
package Stuff; use Moose; use Stuff::Options; has 'options' => ( 'is' => "ro", 'isa' => "Stuff::Options", 'default' => sub { Stuff::Options->new }, ); no Moose; 1;然后在 Stuff/Options.pm 中:
package Stuff::Options; use Moose; has '_options' => ( 'is' => "ro", 'isa' => "ArrayRef[Str]", 'traits' => [ "Array" ], 'default' => sub { [] }, 'handles' => [ qw(elements push map grep first get join count is_empty sort) ], ); no Moose; 1;这将允许您的示例中的代码工作($stuff->options->get(1)).
This would allow code as in your example to work ($stuff->options->get(1)).
更多推荐
Moose:如何获取一组对象?特质?
发布评论