Sha256: 95211df1c035bb152d8b04a5d9594b9f6efd09181d56accfaeae87ad6cd4329e

Contents?: true

Size: 1.13 KB

Versions: 3

Compression:

Stored size: 1.13 KB

Contents

require 'memcache'

class APICache::MemcacheStore < APICache::AbstractStore
  class NotReady < Exception #:nodoc:
    def initialize
      super("Memcache server is not ready")
    end
  end

  class NotDefined < Exception #:nodoc:
    def initialize
      super("Memcache is not defined")
    end
  end
  
  def initialize
    APICache.logger.log "Using memcached store"
    namespace = 'api_cache'
    host = '127.0.0.1:11211'
    @memcache = MemCache.new(host, {:namespace => namespace})
    raise NotReady unless @memcache.active?
    true
  # rescue NameError
  #   raise NotDefined
  end
  
  def set(key, data)
    @memcache.set(key, data)
    @memcache.set("#{key}_created_at", Time.now)
    APICache.logger.log("cache: set (#{key})")
    true
  end
  
  def get(key)
    data = @memcache.get(key)
    APICache.logger.log("cache: #{data.nil? ? "miss" : "hit"} (#{key})")
    data
  end
  
  def exists?(key)
    # TODO: inefficient - is there a better way?
    !@memcache.get(key).nil?
  end
  
  def expired?(key, timeout)
    Time.now - created(key) > timeout
  end
  
  private

  def created(key)
    @memcache.get("#{key}_created_at")
  end
end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
mloughran-api_cache-0.1.1 lib/api_cache/memcache_store.rb
mloughran-api_cache-0.1.2 lib/api_cache/memcache_store.rb
api_cache-0.1.2 lib/api_cache/memcache_store.rb