3
我想添加序列化到一個Moose類,它需要使用自定義的init_arg(屬性名稱前加一個破折號來表示API一致性)的屬性,看起來這會導致解包失敗。我已經在下面設置了一個測試用例來說明我的觀點。如何使用MooseX :: Storage將自定義init_arg的[必需]屬性序列化?
use strict;
use warnings;
package MyClass1;
use Moose;
use MooseX::Storage;
use namespace::autoclean;
with Storage;
has 'my_attr' => (
is => 'ro',
isa => 'Str',
required => 1,
);
__PACKAGE__->meta->make_immutable;
package MyClass2;
use Moose;
use MooseX::Storage;
use namespace::autoclean;
with Storage;
has 'my_attr' => (
is => 'ro',
isa => 'Str',
required => 1,
init_arg => '-my_attr',
);
__PACKAGE__->meta->make_immutable;
package main;
my $inst1 = MyClass1->new(my_attr => 'The String');
my $packed1 = $inst1->pack;
my $unpacked1 = MyClass1->unpack($packed1); # this works
my $inst2 = MyClass2->new(-my_attr => 'The String');
my $packed2 = $inst2->pack;
my $unpacked2 = MyClass2->unpack($packed2); # this fails with a ...
# ... Attribute (my_attr) is required at ...
更新:進一步的調查表明,出現的問題是包裝時init_arg不考慮。因此,即使使用自定義init_arg的非必需屬性在解包後仍未正確恢復。看到這個額外的測試案例:
package MyClass3;
with Storage;
has 'my_attr' => (
is => 'ro',
isa => 'Str',
init_arg => '-my_attr',
);
# in main...
my $inst3 = MyClass3->new(-my_attr => 'The String');
my $packed3 = $inst3->pack;
my $unpacked3 = MyClass3->unpack($packed3); # this seems to work ...
say $unpacked3->my_attr; # ... but my_attr stays undef
非常感謝您的幫助, 丹尼斯
這是最有可能的錯誤。我們目前正在吸引#moose看看誰先看看它。 (隨時加入!:) :) – Ether 2011-02-01 15:58:30