David B
David B

Reputation: 29998

Can I make a Moose attribute "write once"?

I would like to have a non-required Moose attribute that can be set only once.

If I use is => 'ro' I must set the attribute upon creation of the object, but I want to be able to add it afterwards (as long as it's not been set already).

Upvotes: 6

Views: 299

Answers (2)

Pedro Silva
Pedro Silva

Reputation: 4700

Use a method modifier:

has 'attr' => (
    is => 'rw',
    predicate => 'is_set',
    ...
};   

before 'attr' => sub {
     my $self = shift;
     die 'attr already set' if $self->is_set;
};

Upvotes: 5

daxim
daxim

Reputation: 39158

MooseX::SetOnce

Upvotes: 12

Related Questions