Expiration-date 1.1.0 (Screaming Bacon)

expiration-date version 1.1.0
by Tim P.
http://codeforpeople.rubyforge.org/expiration-date
(the “Screaming Bacon” release)

== DESCRIPTION

Really simple caching by attaching an expiration date to attributes.

The ExpirationDate module adss two methods to a class – expiring_attr
and
expiring_class_attr. These two methods are used to declare attributes in
the
instance and in the class, respectively, that will expire after some
period of
seconds have elapsed. The attribute is re-initialized from the given
block
after it has expired. This is a very simple form of caching.

== CHANGES

  • 1 minor enhancement
    • added expiring class attributes

== SYNOPSIS

A simple example demonstrating how the block gets called after the
expiration
time is passed.

class A
include ExpirationDate
expiring_attr( :foo, 60 ) { ‘foo’ }
end

a = A.new
a.foo #=> ‘foo’
a.foo = ‘bar’
a.foo #=> ‘bar’

sleep 61
a.foo #=> ‘foo’

A slightly more useful example. Here we are going to extract information
from a
database every five minutes. This assumes you have the ‘activesupport’
and
‘activerecord’ gems installed.

class MyModel < ::ActiveRecord::Base
include ExpirationDate
expiring_class_attr( :costly_data, 5.minutes ) {
models = MyModel.find( :all, :conditions => [‘costly query
conditions’] )
result = models.map {|m| # costly operations here}
result
}
end

MyModel.costly_data #=> result

Attributes can be expired manually, and the time it takes them to expire
can be
modified as well.

class AgeDemo
include ExpirationDate
expiring_attr( :bar, 120 ) { Time.now }
end

demo = AgeDemo.new
demo.bar #=> now

sleep 60
demo.bar #=> 60 seconds ago

demo.expire_bar_now
demo.bar #=> now

demo.alter_bar_age( 10 )
demo.expire_bar_now
demo.bar #=> now
sleep 11
demo.bar #=> now

Blessings,
TwP

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs