tags:

views:

89

answers:

2

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 provided not class provided method)
+4  A: 

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).

Jesse Luehrs
A: 

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.

fengshaun