05 September 2008
This post may be outdated due to it was written on 2008. The links may be broken. The code may be not working anymore. Leave comments if needed.
I want a scoreboard on MooseX::TheSchwartz.
so I defined one like "has 'scoreboard' => ( is => 'rw', isa => 'Str' );", but that's not what I want for all, I want more.
I want it to be a temp file related to $$ when I set it as 1 or 'on'.
I want I can custom a temp file for it.

I know I can write a method like the one in TheSchwartz. but with Moose, it's much more elegant as what u want!
has 'scoreboard'  => (
is => 'rw',
isa => 'Str',
trigger => sub {
my ($self, $dir) = @_;

return unless $dir;
# no endless loop when it's a file
if ($dir =~ /\/theschwartz\/scoreboard\./is) {
# get the real dir from $dir regardless a file
my (undef, $dir) = File::Spec->splitpath( $dir );
unless (-e $dir) {
mkdir($dir, 0755) or die "Can't create scoreboard directory '$dir': $!";
}
return;
}

# They want the scoreboard but don't care where it goes
if (($dir eq '1') or ($dir eq 'on')) {
$dir = File::Spec->tmpdir();
}

$dir .= '/theschwartz';
unless (-e $dir) {
mkdir($dir, 0755) or die "Can't create scoreboard directory '$dir': $!";
}

$self->{scoreboard} = $dir."/scoreboard.$$";
}
);
now I have all I want.

just be careful, when u want to change itself in trigger like "$self->{scoreboard} = 'xxx'" or "$self->scoreboard('xxx');", u must make sure there isn't a endless loop since change itself will call trigger again.

test code can be found here: http://fayland.googlecode.com/svn/trunk/script/learn_moose/001_attribute_trigger.pl

Thanks.


blog comments powered by Disqus