Only attribute attributes are read-only, and how to set them?

How to set Moose read-only attribute attribute?

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 attributes if you cannot set it in the constructor or at run time? Is there something missing in Moose :: Meta :: Attribute ? Is there any way to install it using meta?

$c->meta->get_attr('ext')->set_value('foo') # doesn't work either (attribute trait provided not class provided method)
+3
source share
2 answers

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 (constructor for the attribute).

+6
source

I use defaultto work with attributes ro:

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

myattr , .

-1

Source: https://habr.com/ru/post/1750568/


All Articles