Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent Perl Moose Read-Only Attributes being set upon a call to new?

I would like to simply declare a read only attribute in Moose that cannot be initialized in a call to new. So after declaring the following:

package SOD::KuuAnalyze::ProdId;

use Moose;

has 'users' => (isa => 'ArrayRef[Str]', is => "ro");

1;

I do not want the following to work:

my $prodid = SOD::KuuAnalyze::ProdId->new(users => ["one", "two"]);
like image 699
ennuikiller Avatar asked Nov 28 '09 22:11

ennuikiller


2 Answers

Use the init_arg attribute configuration (see "Constructor parameters" in Moose::Manual::Attributes):

package SOD::KuuAnalyze::ProdId;
use Moose;

has 'users' => (
    isa => 'ArrayRef[Str]', is => "ro",
    init_arg => undef,    # do not allow in constructor
);
1;
like image 66
Ether Avatar answered Sep 22 '22 19:09

Ether


How about

package SOD::KuuAnalyze::ProdId;

use Moose;

has 'users' => ( isa => 'ArrayRef[Str]', is => 'ro', init_arg => undef, default => sub { [ 'one', 'two' ] } );

Setting the init_arg to undef seems to be necessary to disallow setting the attribute from the constructor.

like image 42
friedo Avatar answered Sep 23 '22 19:09

friedo