Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding a class' "is" attribute (Moose)

Tags:

perl

moose

I am trying to subclass an ro attribute to make it rw like so:

has '+content' => (is => 'rw');

This doesn't seem to work though. Is this not possible?

like image 470
StevieD Avatar asked Nov 09 '22 02:11

StevieD


1 Answers

You should define an object as read-only and then provide a private writer

#!/usr/bin/perl
use Modern::Perl;

{
    package Foo;
    use Moose;

    has bar => (
      is     => 'ro',
      writer => '_set_bar',
  );

}

my $foo = Foo->new;

Then if you try to $foo->bar('something'); you will get the error you mentioned in the comment Cannot assign a value to a read-only accessor and here is the magic you need $foo->_set_bar('something');
Thanks to inheritance it will work thorough Moose framework.

like image 123
farzane Avatar answered Nov 15 '22 05:11

farzane