lib/smoke/cache.rb in benschwarz-smoke-0.4.2 vs lib/smoke/cache.rb in benschwarz-smoke-0.5.0

- old
+ new

@@ -2,43 +2,58 @@ require 'digest/md5' module Smoke class Cache class << self - def configure! - require "moneta/#{Smoke.config[:cache][:store].to_s}" if enabled? - rescue LoadError - Smoke.log.fatal "Cache store not found. Smoke uses moneta for cache stores, ensure that you've chosen a moneta supported store" - end - - def fetch(name, &block) - key = generate_key(name) - output = (enabled?) ? cache[key] : block.call - if output - return output - else - output = block.call - persist(key, output) + def fetch(uri, options) + output = (enabled?) ? read(uri) : query(uri, options) + + unless output.keys.any? + Smoke.log.info "Cache miss" + output = query(uri, options) end - - return output + + output + rescue + query(uri, options) end - + def enabled? Smoke.config[:cache][:enabled] end - private + protected def cache - Moneta.const_get(Smoke.config[:cache][:store]).send(:new, Smoke.config[:cache][:options]) + Moneta.autoload(klass_name.to_sym, file_name) + @@cache ||= Moneta.const_get(klass_name).new(Smoke.config[:cache][:options]) end - - def persist(key, store) - cache.store(key, store, :expire_in => Smoke.config[:config][:cache][:expiry]) + + def file_name + "moneta/#{Smoke.config[:cache][:store].to_s}" end + + def klass_name + Smoke.config[:cache][:store].to_s.camel_case + end + + def query(uri, options) + request = RestClient.get(uri, options) + write(uri, request, request.headers[:content_type]) if enabled? + {:body => request, :content_type => request.headers[:content_type]} + end + + def read(uri) + key = generate_key(uri) + return cache[key] + end + + def write(uri, body, content_type) + store = {:body => body, :content_type => content_type} + self.cache.store(generate_key(uri), store, :expire_in => Smoke.config[:cache][:expiry]) + end def generate_key(key) - Digest::MD5.hexdigest(key) + Digest::MD5.hexdigest(key.to_s) end end end end \ No newline at end of file