Module: Cache

Defined in:
lib/memcache_util.rb

Overview

A utility wrapper around the MemCache client to simplify cache access. All methods silently ignore MemCache errors.

Class Method Summary collapse

Class Method Details

.add(key, value, expiry = 0) ⇒ Object

Sets value in the cache at key, with an optional expiry time in seconds. If key already exists in cache, returns nil.


53
54
55
56
57
58
59
60
61
# File 'lib/memcache_util.rb', line 53

def self.add(key, value, expiry = 0)
  start_time = Time.now
  response = CACHE.add key, value, expiry
  elapsed = Time.now - start_time
  debug('MemCache Add (%0.6f)  %s' % [elapsed, key])
  (response == "STORED\r\n") ? value : nil
rescue MemCache::MemCacheError => err
  debug "MemCache Error: #{err.message}"
end

.debug(message) ⇒ Object


83
84
85
86
87
# File 'lib/memcache_util.rb', line 83

def self.debug(message)
  return nil unless defined? ActiveRecord
  ActiveRecord::Base.logger.debug message
  nil
end

.delete(key, delay = nil) ⇒ Object

Deletes key from the cache in delay seconds.


66
67
68
69
70
71
72
73
# File 'lib/memcache_util.rb', line 66

def self.delete(key, delay = nil)
  start_time = Time.now
  CACHE.delete key, delay
  elapsed = Time.now - start_time
  debug('MemCache Delete (%0.6f)  %s' % [elapsed, key])
rescue MemCache::MemCacheError => err
  debug "MemCache Error: #{err.message}"
end

.get(key, expiry = 0) ⇒ Object

Returns the object at key from the cache if successful, or nil if either the object is not in the cache or if there was an error attermpting to access the cache.

If there is a cache miss and a block is given the result of the block will be stored in the cache with optional expiry, using the add method rather than set.


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/memcache_util.rb', line 16

def self.get(key, expiry = 0)
  start_time = Time.now
  value = CACHE.get key
  elapsed = Time.now - start_time
  debug('MemCache Get (%0.6f)  %s' % [elapsed, key])
  if value.nil? and block_given? then
    value = yield
    add key, value, expiry
  end
  value
rescue MemCache::MemCacheError => err
  debug "MemCache Error: #{err.message}"
  if block_given? then
    value = yield
    put key, value, expiry
  end
  value
end

.put(key, value, expiry = 0) ⇒ Object

Sets value in the cache at key, with an optional expiry time in seconds.


39
40
41
42
43
44
45
46
47
# File 'lib/memcache_util.rb', line 39

def self.put(key, value, expiry = 0)
  start_time = Time.now
  CACHE.set key, value, expiry
  elapsed = Time.now - start_time
  debug('MemCache Set (%0.6f)  %s' % [elapsed, key])
  value
rescue MemCache::MemCacheError => err
  debug "MemCache Error: #{err.message}"
end

.resetObject

Resets all connections to MemCache servers.


78
79
80
81
# File 'lib/memcache_util.rb', line 78

def self.reset
  CACHE.reset
  debug 'MemCache Connections Reset'
end