# Demo :expires\_in with :memory\_store

**URL:** <https://www.ruby-forum.com/t/demo-expires-in-with-memory-store/162368>\
**Category:** Rails\
**Created:** [March 9, 2009, 10:03am UTC](https://www.ruby-forum.com/t/demo-expires-in-with-memory-store/162368 "2009-03-09T10:03:46Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![axgle](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/9de0a6/32.png) [@axgle](https://www.ruby-forum.com/u/axgle)\
**Post date:** [March 9, 2009, 10:03am UTC](https://www.ruby-forum.com/t/demo-expires-in-with-memory-store/162368/1 "2009-03-09T10:03:46Z")

</div>

require ‘rubygems’  
require ‘active\_support’  
cache = ActiveSupport::Cache.lookup\_store(:memory\_store)  
#cache=Rails.cache  
def cache.fetch(key,options={})  
second=options.delete(:expires\_in).to\_i  
raise “cache\_fetch method second can not blow zero” if second\<=0  
time\_tag = ((Time.now.to\_i/second)\*second)

```
    expires_key = [time_tag,key]

```

p expires\_key  
instance\_eval{@data.delete\_if{|k,v|  
Time.now.to\_i\>k.first+second}}  
super(expires\_key,options){yield}  
end

puts cache.fetch(‘test’,:expires\_in=\>3.seconds){rand}  
puts cache.fetch(‘test’,:expires\_in=\>3.seconds){rand}  
sleep 4  
puts cache.fetch(‘test’,:expires\_in=\>3.seconds){rand}
