Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I best make triggered accessors with defaults in Moose?
    text
    copied!<p>I have a situation where I'd like to cache some calculations for use later. Let's say I have a list of allowed values. Since I'm going to be checking to see if anything is in that list I'm going to want it as a hash for efficiency and convenience. Otherwise I'd have to grep.</p> <p>If I'm using Moose it would be nice if the cache was recalculated each time the list of allowed values is changed. I can do that with a trigger easy enough...</p> <pre><code>has allowed_values =&gt; ( is =&gt; 'rw', isa =&gt; 'ArrayRef', trigger =&gt; sub { my %hash = map { $_ =&gt; 1 } @{$_[1]}; $_[0]-&gt;allowed_values_cache(\%hash); } ); has allowed_values_cache =&gt; ( is =&gt; 'rw', isa =&gt; 'HashRef', ); </code></pre> <p>And the two will stay in sync...</p> <pre><code>$obj-&gt;allowed_values([qw(up down left right)]); print keys %{ $obj-&gt;allowed_values_cache }; # up down left right </code></pre> <p>Now let's say I want a default for <code>allowed_values</code>, simple enough change...</p> <pre><code>has allowed_values =&gt; ( is =&gt; 'rw', isa =&gt; 'ArrayRef', trigger =&gt; sub { my %hash = map { $_ =&gt; 1 } @{$_[1]}; $_[0]-&gt;allowed_values_cache(\%hash); }, default =&gt; sub { return [qw(this that whatever)] }, ); </code></pre> <p>...except setting the default doesn't call the trigger. To get it to DWIM I need to duplicate the caching.</p> <pre><code>has allowed_values =&gt; ( is =&gt; 'rw', isa =&gt; 'ArrayRef', trigger =&gt; sub { $_[0]-&gt;cache_allowed_values($_[1]); }, default =&gt; sub { my $default = [qw(this that whatever)]; $_[0]-&gt;cache_allowed_values($default); return $default; }, ); sub cache_allowed_values { my $self = shift; my $values = shift; my %hash = map { $_ =&gt; 1 } @$values; $self-&gt;allowed_values_cache(\%hash); return; } </code></pre> <p>The Moose docs are explicit about <code>trigger</code> not getting called when the default is set, but it gets in the way. I don't like the duplication there.</p> <p>Is there a better way to do it?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload