2010-06-17 69 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的价值其他地方,则使用默认。