Module: ModelCache

Defined in:
lib/model-cache.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

DEFAULT_TIME =
12*3600
NIL_OBJECT =
:__i_have_no_idea_how_to_do_this_without_an_ugly_symbol

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.cache(ckey, time = DEFAULT_TIME, &block) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/model-cache.rb', line 16

def self.cache(ckey, time = DEFAULT_TIME, &block)
 ckey = ckey.hash.to_s(16)
 cache_hit = false
  if CACHE.class.name == 'Memcached'
    begin
      result = CACHE.get(ckey.hash.to_s)
      cache_hit = true
    rescue Memcached::NotFound => e
    end
  elsif CACHE.class.name == 'MemCache' or CACHE.class.name == 'Dalli::Client'
    result = CACHE.get(ckey.hash.to_s)
    if result
      cache_hit = true
    end
    if result == NIL_OBJECT
      result = nil
    end
  else
    raise "CACHE object not configured #{CACHE.inspect}!"
  end
  unless cache_hit
    result = block.call
    if CACHE.class.name == 'MemCache' or CACHE.class.name == 'Dalli::Client'
      if result
        CACHE.set(ckey.hash.to_s, result, time)
      else
        CACHE.set(ckey.hash.to_s, NIL_OBJECT, time)
      end
    elsif CACHE.class.name == 'Memcached'
      CACHE.set(ckey.hash.to_s, result, time)
    else
      raise "CACHE object not configured #{CACHE.inspect}!"
    end
    result
  end
  result
end

.included(klass) ⇒ Object



8
9
10
# File 'lib/model-cache.rb', line 8

def self.included(klass)
 klass.extend ClassMethods
end

Instance Method Details

#cache(key, time = DEFAULT_TIME, &block) ⇒ Object



12
13
14
# File 'lib/model-cache.rb', line 12

def cache(key, time = DEFAULT_TIME, &block)
 ModelCache::cache([self.cache_key, key], time, &block)
end