Moose read-only Attribute Traits and how to set them?
How do I set a Moose read only attribute trait?
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
What is the purpose of Read Only attribute traits if you can't set it in the constructor or in runtime? Is there something I'm missing in Moose::Meta::Attribute? Is there a way to set it using meta
?
$c->meta->get_attr('ext')->set_value('foo') # doesn't work either (attribute trait 开发者_JS百科provided not class provided method)
You can set it in the constructor:
package Class;
has 'foo' => ( isa => 'Str', is => 'ro', ext => 'whatever', traits => ['AttrTrait'] );
You just need to pass it to the right constructor (the constructor for the attribute).
I use default
to deal with ro
attributes:
package Foo;
use Moose;
has 'myattr' => (is => 'ro', default => 'my value goes here');
And since you won't be setting myattr
's value anywhere else, the default is used.
精彩评论