Skip to content

Instantly share code, notes, and snippets.

@ab5tract
Created September 4, 2008 19:31
Show Gist options
  • Save ab5tract/8854 to your computer and use it in GitHub Desktop.
Save ab5tract/8854 to your computer and use it in GitHub Desktop.
Waves Gets Cached
module Waves
class Cache
attr_accessor :cache
def initialize
@cache = {}
end
def [](key)
fetch(key)
end
def []=(key,value)
store(key,value)
end
def store(key, value, ttl = {})
@cache[key] = {
:expires => ttl.is_a?(Number) ? Time.now + ttl : nil,
:value => value
}
end
def delete(keys*)
keys.each {|key| @cache[key].delete }
end
def clear
@cache.clear
end
def fetch(key)
if (@cache[key][:expires] > Time.now) or (@cache[key][:expires].nil?)
@cache[key][:value]
else
@cache[key][:value]
@cache[key].delete
end
end
end
end
module Waves
module Layers
class FileCache < Waves::Cache
def initialize(dir)
@directory = dir
super
end
def store(key, value, ttl = {})
super(key, value, ttl)
key_file = @directory / key
file = File.new(key_file,'w') unless File.exists?(key_file)
Marshal.dump(@cache[key], file)
file.close
end
def delete(*keys)
keys.each {|key| File.delete(@directory / key) }
super keys
end
def clear
@cache.each_key {|key| File.delete(@directory / key) }
super
end
def fetch(key)
raise "No cache found for #{key}" unless File.exists?(@directory / key)
@cache[key] = Marshal.load(@directory / key)
if (@cache[key][:expires] > Time.now) or (@cache[key][:expires].nil?)
@cache[key][:value]
else
@cache[key][:value]
delete(key)
end
end
end
end
end
require File.join(File.dirname(__FILE__) , "helpers")
def fill_cache(cache)
cache[:key1] = "value1"
cache[:key2] = "value2"
end
describe "Waves::Cache" do
before do
cache = Waves::Cache.new
fill_cache cache
end
it "can find a value in the cache" do
cache[:key1].should == "value1"
end
it "can delete a value from the cache" do
fill_cache cache
cache.delete(:key1)
cache[:key1].should == nil
cache[:key2].should == "value2"
end
it "can clear the cache" do
fill_cache cache
cache.clear
cache[:key1].should == nil
cache[:key2].should == nil
end
end
require 'layers/cache/file_cache'
describe "Waves::Layers::FileCache" do
before do
cache = Waves::Layers::FileCache.new('.')
fill_cache cache
end
it "can find a value in the cache" do
cache[:key1].should == "value1"
end
it "can delete a value from the cache" do
fille_cache cache
cache.delete(:key1)
cache[:key1].should == nil
cache[:key2].should == "value2"
end
it "can clear the cache" do
fill_cache cache
cache.clear
cache[:key1].should == nil
cache[:key2].should == nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment