Moose: Loading an Object from a File into a BUILD Method
I need to read a file in the BUILD method and I want to use the MooseX :: Storage package download method.
But this load method creates a new object, so when I set the object, it is not an object read from a file. In the code below, I am creating a $ m1 object with state 2 to write a file, I am creating $ m2 without a parameter to read the file, but $ m2 does not contain the correct value. Package:
package mia;
use Moose;
use MooseX::Storage;
with Storage(format => 'JSON', io => 'File');
has 'nome' => ( is => 'rw', isa => 'Str', default =>'',);
has 'stato' => ( is => 'rw', isa => 'Int', default =>1,);
sub BUILD{
my $self=shift;
if ($self->stato==1){
$self=mia->load("mia.dat");
}
if ($self->stato==2){
$self->stato(0);
$self->nome("prova");
$self->store("mia.dat");
}
sub stampa(){
my $self=shift;
print $self->nome." ".$self->stato;
}
main program
use mia;
my $m;
$m1=mia->new(stato=>2);
$m2=mia->new();
print "\nm1 \n";
$m1->stampa();
print "\nm2 \n";
$m2->stampa();
+2
a source to share
1 answer
Your code seems to act like BUILD is a constructor that doesn't exist - it's more like a post-construction hook, where you can do other things like reading values from the DB. You should also:
- store the result
mia->load
in an attribute and possibly use delegated methods to access it, or - use the result
mia->load
as an object rather than create a separate file.
Here's an example of the first case, separating the MooseX :: Storage object from the object that controls it:
package miaController;
use Moose;
use mia;
has 'nome' => ( is => 'rw', isa => 'Str', default =>'',);
has 'stato' => ( is => 'rw', isa => 'Int', default =>1,);
has 'mia' => ( is => 'rw', isa => 'mia', lazy => 1);
sub BUILD
{
my $self = shift;
if ($self->stato == 1)
{
$self->mia(mia->load("mia.dat"));
}
elsif ($self->stato == 2)
{
$self->stato(0);
$self->nome("prova");
$self->mia->store("mia.dat");
}
}
sub stampa
{
my $self = shift;
print $self->nome." ".$self->stato;
}
package mia;
use Moose;
use MooseX::Storage;
with Storage(format => 'JSON', io => 'File');
package main:
use miaController;
my $m1=miaController->new(stato=>2);
my $m2=miaController->new();
print "\nm1 \n";
$m1->stampa();
print "\nm2 \n";
$m2->stampa();
+5
a source to share