# Copyright:: Copyright (c) 2007-2008 Mark Bates class Cachetastic::Caches::Base # everything is done at the class level. there won't be any 'instances of it' # using class << self means we don't have to prefix each method with 'self.' class << self def get(key) res = nil do_with_logging(:get, key) do res = store.get(key.to_s) if res.nil? res = yield if block_given? else res = unmarshall(res) end res end res end def set(key, value, expiry = (store.all_options["default_expiry"] || 0)) do_with_logging(:set, key) do exp_swing = store.all_options["expiry_swing"] if exp_swing swing = rand(exp_swing.to_i) case rand(2) when 0 expiry = (expiry.to_i + swing) when 1 expiry = (expiry.to_i - swing) end end store.set(key.to_s, marshall(value), expiry.to_i) logger.info('', '', :expiry, cache_name, key, expiry.to_i) value end end alias_method :put, :set def delete(key, delay = 0) do_with_logging(:delete, key) do store.delete(key.to_s, delay) end end def expire_all store.expire_all logger.info('', '', :expired, cache_name) end def cache_name self.name.methodize end def store cache_conn_instance.get(cache_name) end def logger store.logger end private def marshall(value) return case store.all_options["marshall_method"] when "yaml" YAML.dump(value) else value end end def unmarshall(value) return case store.all_options["marshall_method"] when "yaml" YAML.load(value) else value end end def cache_conn_instance Cachetastic::Connection.instance end def do_with_logging(action, key) start_time = Time.now logger.info(:starting, action, cache_name, key) res = yield if block_given? end_time = Time.now str = "" unless res.nil? str = "[#{res.class.name}]" str << "\t[Size = #{res.size}]" if res.respond_to? :size str << "\t" << res.inspect if store.debug? end logger.info(:finished, action, cache_name, key, (end_time - start_time), str) res end # make sure people can't instaniate this object! def new(*args) raise MethodNotImplemented.new("You can not instaniate this class!") end end end