2010-06-17 67 views
3

如何設置Moose只讀屬性特徵?Moose只讀屬性特徵以及如何設置它們?

package AttrTrait; 
use Moose::Role; 
has 'ext' => (isa => 'Str', is => 'ro'); 

package Class; 
has 'foo' => (isa => 'Str', is => 'ro', traits => [qw/AttrTrait/]); 

package main; 
my $c = Class->new(foo => 'ok'); 
$c->meta->get_attribute('foo')->ext('die') # ro attr trait 

什麼是閱讀的目的只有屬性特質,如果你不能將其設置在構造函數或運行時?有什麼我在Moose::Meta::Attribute失蹤?有沒有辦法使用meta進行設置?

$c->meta->get_attr('ext')->set_value('foo') # doesn't work either (attribute trait provided not class provided method) 

回答

6

您可以在構造函數中進行設置:

package Class; 
has 'foo' => (isa => 'Str', is => 'ro', ext => 'whatever', traits => ['AttrTrait']); 

你只需將它傳遞給正確的構造函數(構造函數的屬性)。

-1

我用default處理ro屬性:

package Foo; 
use Moose; 
has 'myattr' => (is => 'ro', default => 'my value goes here'); 

而且因爲你將不會被設置myattr的價值其他地方,則使用默認。