Sha256: ea5d1134fdfcaf8b9d7a4e89eab0edce2d920a1ff300ff07268e797d54144d01

Contents?: true

Size: 1.44 KB

Versions: 7

Compression:

Stored size: 1.44 KB

Contents

require 'moneta'
require 'digest/md5'

module Smoke
  class Cache
    class << self
      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
        
        output
      rescue
        query(uri, options)
      end

      def enabled?
        Smoke.config[:cache][:enabled]
      end
  
      protected
      def cache
        Moneta.autoload(klass_name.to_sym, file_name)
        @@cache ||= Moneta.const_get(klass_name).new(Smoke.config[:cache][:options])
      end
            
      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.to_s)
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
benschwarz-smoke-0.5.0 lib/smoke/cache.rb
benschwarz-smoke-0.5.1 lib/smoke/cache.rb
benschwarz-smoke-0.5.2 lib/smoke/cache.rb
benschwarz-smoke-0.5.3 lib/smoke/cache.rb
benschwarz-smoke-0.5.4 lib/smoke/cache.rb
benschwarz-smoke-0.5.5 lib/smoke/cache.rb
benschwarz-smoke-0.5.6 lib/smoke/cache.rb