I'm relatively new to Moose. I'm trying to add the concept of a cached attribute. Essentially, there is a timestamp that is associated with an attribute, which is checked on each access. If the timestamp is older than a certain threshold, the value gets cleared (by the clearer function), and then the value will automatically be refetched (e.g. from the Database) by the build function.

The code to do the timers and database fetch is very straightforward.

What is less straightforward is the best way to do this in Moose. I have a somewhat reasonable solution, but I'd bet someone will have a far more elegant solution.

My solution works like this: you must declare an "around" method modifier, and pass the name of the attribute to a utility function. The utility function will automatically create a timer associated with the attribute (if needed), as well as reset the timer, and call the clearer method.

It occurs to me that this could be done more cleanly. For one, in the around method I must specify the name of the attribute twice. This allows me to use the same function (named "around_timer_cached" below) generically for all the attributes (note that the around method modifier passes the coderef, but not the attribute, which seems like a flaw). E.g.

around 'some_attribute' => sub { around_timer_cached ('some_attribute' +, @_) };

Is there a more elegant way to get the attribute name in the called "around" method? Also, is there a way to extend the attribute system so that this could just be yet another declarative parameter passed into the "has" decl (e.g. cached_secs => 600).

Finally, has someone already done such extensions to the attribute system?


In reply to Extending Moose by zerohero

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.