Class: Cache
Overview
A simple file caching mechanism with automatic timeout.
Direct Known Subclasses
Instance Method Summary collapse
-
#cache(id, timeout = @timeout) ⇒ Object
Add a cached item to
id
. -
#initialize(cache, timeout = 24) ⇒ Cache
constructor
Create a cache at
cache
path for a giventimeout
(in hours).
Constructor Details
#initialize(cache, timeout = 24) ⇒ Cache
Create a cache at cache
path for a given timeout
(in hours).
13 14 15 16 |
# File 'lib/dep_analyzer.rb', line 13 def initialize(cache, timeout=24) @cache = cache @timeout = timeout end |
Instance Method Details
#cache(id, timeout = @timeout) ⇒ Object
Add a cached item to id
. Value is returned either from the cache if it is new enough or by yielding.
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/dep_analyzer.rb', line 22 def cache(id, timeout=@timeout) Dir.mkdir @cache unless test ?d, @cache path = File.join @cache, id age = test(?f, path) ? (Time.now - test( ?M, path )) / 3600 : -1 if age >= 0 and timeout > age then warn "from cache" if $DEBUG data = File.read(path) else warn "NOT from cache (#{age} hours old)" if $DEBUG data = yield File.open(path, "w") do |f| f.write data end end return data end |