5

次のサブタイプと強制チェーンで何が欠けていますか? 検証済みの型の配列参照を強制するか、次の入力から死ぬことができるようにしたいと思います。

  • 強制文字列
  • 有効な文字列
  • 強制可能な文字列と有効な文字列が混在する配列参照

validateすべての型が完全に名前空間化されており、宣言されていない関数とcoerce_str検証 (bool を返す) と強制が行われ、入力から有効な文字列が返されると仮定します。

subtype 'CustomType'
  => as 'Str'
    => where { validate($_) }
  ;

coerce 'CustomType'
  => from 'Str'
    => via { if (my $coerced = coerce_str($_)) {
               return $coerced;
             } 
             return $_;
           }
  ;

subtype 'ArrayRefofCustomTypes'
  => as 'ArrayRef[CustomType]'
  ;

coerce 'ArrayRefofCustomTypes'
  => from 'CustomType'
    => via { [ $_ ] }
  ;

has 'values' => ( is => 'ro', required => 1,
                  isa => 'ArrayRefofCustomTypes', 
                  coerce => 1,
                );

CustomType が機能することはわかっています。属性をそのまま定義し、強制可能な文字列または既に有効な文字列を使用してオブジェクトを初期化できるためです。どうすればよいかよくわかりませんが、渡された arrayref をコンストラクターから掘り下げて、含まれているすべての文字列を個別に検証することを明示的に処理することです。ディープ強制に関するドキュメント ( http://search.cpan.org/dist/Moose/lib/Moose/Manual/Types.pod#Deep_coercion ) を数回読んだことがありますが、よく理解できていません。誰かが私を正しい方向に向けることができることを願っています。ありがとう!

ここでは、より簡潔に概説するためにそれを切り詰めましたが、次のとおりです。

{ 
  package My::Class;

  use strict;
  use warnings;

  use Moose;
  use Moose::Util::TypeConstraints;

  subtype 'CustomType'
    => as 'Str'
      => where { validate($_) }
    ;

  coerce 'CustomType'
    => from 'Str'
      => via { if (my $coerced = coerce_str($_)) {
                 return $coerced;
               } 
               return $_;
             }
    ;

  subtype 'ArrayRefofCustomTypes'
    => as 'ArrayRef[CustomType]'
    ;

  coerce 'ArrayRefofCustomTypes'
    => from 'CustomType'
      => via { [ $_ ] }
    ;

  has 'values' => ( is => 'ro', required => 1,
                    isa => 'ArrayRefofCustomTypes', 
                    coerce => 1,
                  );

  sub validate {
    my $val = shift;
    if ($val =~ /^\w+$/) {
      return 1;
    }
    return ();
  }

  sub coerce_str {
    my $val = shift;
    $val =~ s/\W/_/g;
    return $val;
  }
}

{
  package main;

  use strict;
  use warnings;
  use Test::More qw/no_plan/;

  new_ok( 'My::Class' => [ values => [ 'valid' ] ]); #ok
  new_ok( 'My::Class' => [ values => [ qw/valid valid still_valid/ ] ]); #ok
  new_ok( 'My::Class' => [ values => 'valid' ]); # ok
  new_ok( 'My::Class' => [ values => [ 'invalid; needs some coercion - ^&%&^' ] ]); #not ok
  new_ok( 'My::Class' => [ values => 'invalid; needs some coercion - ^&%&^' ]); # not ok
  cmp_ok( My::Class::coerce_str('invalid; needs some coercion - ^&%&^'), 'eq', 'invalid__needs_some_coercion________', 'properly coerces strings'); #ok

}

それをそのまま実行すると、以下が得られます。問題は検証ではありませんが、強制を明示的に定義していないため、何が欠けているのかわかりません。

ok 1 - The object isa My::Class
ok 2 - The object isa My::Class
ok 3 - The object isa My::Class    
not ok 4 - new() died
#   Failed test 'new() died'
#   at testcoercion.pl line 63.
#     Error was:  Attribute (values) does not pass the type constraint because: Validation failed for 'ArrayRefofCustomTypes' with value [ "invalid; needs some coercion - ^&%&^" ] at C:/strawberry/perl/site/lib/Moose/Meta/Attribute.pm line 1131

<< cut >>

not ok 5 - new() died
#   Failed test 'new() died'
#   at testcoercion.pl line 64.
#     Error was:  Attribute (values) does not pass the type constraint because: Validation failed for 'ArrayRefofCustomTypes' with value "invalid; needs some coercion - ^&%&^" at C:/strawberry/perl/site/lib/Moose/Meta/Attribute.pm line 1131

<< cut >>

ok 6 - properly coerces strings
1..6
# Looks like you failed 2 tests of 6.
4

2 に答える 2

2

使用したものはすべて正常に動作するはずです。たとえば、次のテストを検討してください。

my $customtype = Moose::Util::TypeConstraints::find_type_constraint('CustomType');
print "'a' validates as customtype? ", ($customtype->check('a') ? 'yes' : 'no'), "\n";

my $arraytype = Moose::Util::TypeConstraints::find_type_constraint('ArrayRefofCustomTypes');
print "[ 'a' ] validates as array? ", ($arraytype->check([ 'a' ]) ? 'yes' : 'no'), "\n";

{
    package Class;
    use Moose;
    has 'values' => ( is => 'ro', required => 1,
                      isa => 'ArrayRefofCustomTypes',
                      coerce => 1,
                    );
}

my $obj = Class->new(values => 'a');
print $obj->dump(2);

これは以下を出力します:

'a' validates as customtype? yes
[ 'a' ] validates as array? yes
$VAR1 = bless( {
                 'values' => [
                               'a'
                             ]
               }, 'Class' );

結論: 問題が発生している場合、それは他のコードにあります。期待どおりに動作しないコードを貼り付けていただけますか?

于 2011-06-22T20:13:11.917 に答える
2

そうです、強制は、取得したい入力のすべての順列に対して、基本型からカスタム型まで明示的に定義する必要があります。強制と検証のコードをサブルーチンに移動すると、コードの重複を防ぐのに役立ちますが、完全になくなるわけではありません。次のコードは、期待どおりに機能し、それを証明するための TAP 計画もあります。

ただし、機能している間は、この種のことを処理するための意図された方法であるとは絶対に確信していません. 基本型から arrayref カスタム型への明示的なキャストが多数行われていますが、アクセサーが複数の型を強制的に受け入れる場合、これがより大きなコンテキストでうまく機能するかどうかはわかりません。

編集: 実際には、この時点でcoerce 'ArrayRefofCustomTypes' => from 'CustomType'は完全に不要=> from 'Str'です。 は有効な入力と無効な入力の両方を処理します。

{ 
  package My::Class;

  use strict;
  use warnings;

  use Moose;
  use Moose::Util::TypeConstraints;

  subtype 'CustomType'
    => as 'Str'
      => where { validate_cust($_) }
    ;

  coerce 'CustomType'
    => from 'Str'
      => via { coerce_str_to_cust($_) }
    ;

  subtype 'ArrayRefofCustomTypes'
    => as 'ArrayRef[CustomType]'
    ;

  coerce 'ArrayRefofCustomTypes'
    => from 'CustomType'
      => via { [ $_ ] }
    => from 'ArrayRef[Str]'
      => via { [ map { coerce_str_to_cust($_) } @$_ ] }
    => from 'Str'
      => via { [ coerce_str_to_cust($_) ] }
    ;

  has 'values' => ( is => 'ro', required => 1,
                    isa => 'ArrayRefofCustomTypes', 
                    coerce => 1,
                  );

  sub validate_cust {
    my $val = shift;
    if ($val =~ /^\w+$/) {
      return 1;
    }
    return ();
  }

  sub coerce_str_to_cust {
    my $val = shift;
    my $coerced = $val;
    $coerced =~ s/\s/_/g;

    if (validate_cust($coerced)) {
      return $coerced;
    }
    else {
      return $val;
    }
  }
}

{
  package main;

  use strict;
  use warnings;
  use Test::More tests => 12;
  use Test::Exception;

  new_ok( 'My::Class' => [ values => [ 'valid' ] ]);
  new_ok( 'My::Class' => [ values => [ qw/valid valid still_valid/ ] ]);
  new_ok( 'My::Class' => [ values => 'valid' ]);
  new_ok( 'My::Class' => [ values => [ 'invalid and needs some coercion' ] ]);
  new_ok( 'My::Class' => [ values => 'invalid and needs some coercion' ]);
  new_ok( 'My::Class' => [ values => [ 'valid', 'valid', 'invalid and needs some coercion' ] ]);
  throws_ok { my $obj =  My::Class->new( values => [ q/can't be coerced cause it has &^%#$*&^%#$s in it/ ] ); } qr/Attribute \(values\) does not pass the type constraint because: Validation failed/, 'throws exception on uncoercible input';

  my $uncoercible = q/can't be coerced cause it has &^%#$*&^%#$s in it/;
  cmp_ok( My::Class::coerce_str_to_cust('invalid and needs some coercion'), 'eq', 'invalid_and_needs_some_coercion', 'properly coerces strings');
  cmp_ok( My::Class::coerce_str_to_cust($uncoercible), 'eq', $uncoercible , 'returns uncoercible strings unmodified');
  ok( My::Class::validate_cust('valid'), 'valid string validates');
  ok( My::Class::validate_cust(My::Class::coerce_str_to_cust('invalid and needs some coercion')), 'coerced string validates');
  ok( !My::Class::validate_cust('invalid and needs some coercion'), "invalid string doesn't validate");
}
于 2011-06-23T13:54:57.760 に答える