2013-10-27 4 views
3

이 가지고있는 무스 속성 유형으로 변환 :올바른 방법으로 정의하고

package MyPath; 
use strict; 
use warnings; 
use Moose; 

has 'path' => (
    is => 'ro', 
    isa => 'Path::Class::Dir', 
    required => 1, 
); 
1; 

을하지만 같은 두 가지 방법으로이 객체를 생성합니다 :

use strict; 
use warnings; 
use MyPath; 
use Path::Class; 
my $o1 = MyPath->new(path => dir('/string/path')); #as Path::Class::Dir 
my $o2 = MyPath->new(path => '/string/path'); #as string (dies - on attr type) 

그리고 때 'str을'로 전화 - 희망을 두 클래스 :: 경로 :: 디렉터리에 MYPATH 패키지에 내부적으로 변환, 그래서 : $o1->path$o2->path가 반환해야 축복 나는 defin을 확장하려고 Path::Class::Dir

다음에 ition : 그것은 작품을 수행하고 여전히 "다소"는 package MyPath에 자동으로 내부적으로 StrPath::Class::Dir에 변환이 필요

has 'path' => (
    is => 'ro', 
    isa => 'Path::Class::Dir|Str', #allowing both attr types 
    required => 1, 
); 

...

누군가가 나에게 몇 가지 힌트를 줄 수 있을까?

편집 :

좀 더 힌트를주세요 ... 아직

coerce Directory, 
    from Str,  via { Path::Class::Dir->new($_) }; 

has 'path' => (
    is => 'ro', 
    isa => 'Directory', 
    required => 1, 
); 

그러나이 올바르게 사용하는 방법을 생각를 havent : Oesor의 힌트를 바탕으로 난 내가가 someting 등이 필요 이상으로 발견?

답변

5

.

use Moose; 
use Moose::Util::TypeConstraints; 
use Path::Class::Dir; 

subtype 'Path::Class::Dir', 
    as 'Object', 
    where { $_->isa('Path::Class::Dir') }; 

coerce 'Path::Class::Dir', 
    from 'Str', 
     via { Path::Class::Dir->new($_) }; 

has 'path' => (
    is  => 'ro', 
    isa  => 'Path::Class::Dir', 
    required => 1, 
    coerce => 1, 
); 
+0

감사합니다. – novacik

+1

당신의'subtype 'Path :: Class :: Dir'...'선언은'class_type 'Path :: Class :: Dir';'으로 더 자연스럽게 작성 될 수 있습니다. – hobbs

0

힌트 - 값을 강제하는 방법을 찾아 : 당신은 타입 coersion을 찾고

https://metacpan.org/pod/Moose::Manual::Types

+0

몇 가지 힌트를 추가 할 수 있습니까? 나는 내 질문을 편집했다 ... (아마도 1-2 줄이 더 필요하다 - 나에게 답을 주시겠습니까? :) – novacik

관련 문제