Beefy Boxes and Bandwidth Generously Provided by pair Networks Joe
There's more than one way to do things
 
PerlMonks  

Moose: I want builder method to run every time I call an attribute

by italdesign (Novice)
on Sep 26, 2013 at 22:18 UTC ( #1055910=perlquestion: print w/ replies, xml ) Need Help??
italdesign has asked for the wisdom of the Perl Monks concerning the following question:

Hi fellas. Thanks to your help, I've been getting down with Moose. ;-) Now I have a builder method for a logfile attribute. It checks if the logfile exists, and if so, call it logfile-2.txt, logfile-3.txt, and so on. Here's the code:
has 'cmd_logfile' => ( is => 'ro', isa => 'Str', required => 0, la +zy => 1, builder => '_build_cmd_logfile' ); sub _build_cmd_logfile { my $self = shift; my $inner = $self->dl_inner_dir; defined $inner or die "Error: DL_ +INNER_DIR not set."; my $b4_ext = "$inner/transfer"; my $ext = "log"; my $filename = "$b4_ext.$ext"; my $i = 2; while (-s $filename) { $filename = "$b4_ext-$i.$ext"; $i++; } return $filename; }
Trouble is, the builder method only gets run the first time I call the attribute. Subsequent calls of the attribute seems to just use the value already stored in it. This defeats checking for existence since the attribute will always just have the default logfile name and will overwrite it freely (later in the application). I want the builder, or at least its behavior, to run whenever the attribute is called. What's the right way to do it?

Comment on Moose: I want builder method to run every time I call an attribute
Download Code
Re: Moose: I want builder method to run every time I call an attribute
by chromatic (Archbishop) on Sep 26, 2013 at 22:52 UTC

    Don't make it an attribute:

    sub cmd_logfile { my $self = shift; my $inner = $self->dl_inner_dir; defined $inner or die "Error: DL_ +INNER_DIR not set."; my $b4_ext = "$inner/transfer"; my $ext = "log"; my $filename = "$b4_ext.$ext"; my $i = 2; while (-s $filename) { $filename = "$b4_ext-$i.$ext"; $i++; } return $filename; }

      I concur with chromatic. That said, if there are some other factors in play that preclude doing this, you might consider using an around statement in conjunction with the attribute reader to handle any pre-processing needed. You might not even need to have an explicit builder in that case.

      On time, cheap, compliant with final specs. Pick two.

        Two perfect examples of how Moose encourages bad OO design.

        - tye        

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1055910]
Approved by davido
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (11)
As of 2014-04-17 05:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (439 votes), past polls