class EOAT::Cache::MemcachedCache

Memcached cache handler. Used ‘gem memcache` Default use standard connection parameters. @author Ivan Kotov {i.s.kotov.ws e-mail} @example Set Memcached as a cache storage, with default Memcached `address` and `port`

EOAT.cache = EOAT::Cache::MemcachedCache.new

@example Set Redis as a cache storage, with connect to custom server:port and not set key prefix

EOAT.cache = EOAT::Cache::MemcachedCache.new('10.0.1.1:11212', '')

Public Class Methods

new(server='localhost:11211', prefix='eoat') click to toggle source

@param [String] server the connection string ‘<ip-address>:<port>` @param [String] prefix the prefix for keys

# File lib/eoat/cache/memcached_cache.rb, line 15
def initialize(server='localhost:11211', prefix='eoat')
  require 'memcache'

  @backend = Memcache.new(:server => server, :namespace => prefix, :segment_large_values => true)
end

Public Instance Methods

get(host, uri) click to toggle source

Get object from cache @param [String] host the request host string @param [String] uri the query string @return [Object, NilClass] the instance of result class

or nil if key not does not exist
# File lib/eoat/cache/memcached_cache.rb, line 26
def get(host, uri)
  # Set key as md5 string
  key = EOAT::Cache.md5hash(host + uri)
  response = @backend.get(key)
  if response
    if EOAT::Cache.md5hash(response) == @backend.get(key + '_hash')
      return YAML::load(response)
    else
      @backend.delete(key)
      @backend.delete(key + '_hash')
    end
  end
  false
end
save(host, uri, content) click to toggle source

Save instance of result class. @param [String] host the request host string @param [String] uri the query string @param [Object] content the result class instance

# File lib/eoat/cache/memcached_cache.rb, line 45
def save(host, uri, content)
  # Calculate TTL in seconds
  expire = (content.cached_until - content.request_time).to_i
  # If TTL > EOAT.max_ttl set EOAT.max_tt as expire
  expire = expire > EOAT.max_ttl ? EOAT.max_ttl : expire
  # If 0 or a negative value, it does not save.
  if expire > 0
    # Set key as md5 string
    key = EOAT::Cache.md5hash(host + uri)
    yaml = content.to_yaml
    @backend.set(
        key,
        yaml,
        :expiry => expire
    )
    @backend.set(
        key + '_hash',
        EOAT::Cache.md5hash(yaml),
        :expiry => expire
    )
  end
end