Module: Cash::Accessor::ClassMethods

Defined in:
lib/cash/accessor.rb

Instance Method Summary collapse

Instance Method Details

#add(key, value, options = {}) ⇒ Object



40
41
42
# File 'lib/cash/accessor.rb', line 40

def add(key, value, options = {})
  repository.add(cache_key(key), value, options[:ttl] || 0, options[:raw])
end

#cache_key(key) ⇒ Object



66
67
68
# File 'lib/cash/accessor.rb', line 66

def cache_key(key)
  "#{name}/#{key.to_s.gsub(' ', '+')}"
end

#decr(key, delta = 1, ttl = 0) ⇒ Object



55
56
57
58
59
60
# File 'lib/cash/accessor.rb', line 55

def decr(key, delta = 1, ttl = 0)
  repository.decr(cache_key(key), delta) || begin
    repository.set(cache_key(key), (result = yield).to_s, ttl, true)
    result
  end
end

#expire(key) ⇒ Object



62
63
64
# File 'lib/cash/accessor.rb', line 62

def expire(key)
  repository.delete(cache_key(key))
end

#fetch(keys, options = {}, &block) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/cash/accessor.rb', line 11

def fetch(keys, options = {}, &block)
  case keys
  when Array
    keys = keys.collect { |key| cache_key(key) }
    hits = repository.get_multi(keys)
    if (missed_keys = keys - hits.keys).any?
      missed_values = block.call(missed_keys)
      hits.merge!(Hash[*missed_keys.zip(Array(missed_values)).flatten])
    end
    hits
  else
    repository.get(cache_key(keys), options[:raw]) || (block ? block.call : nil)
  end
end

#get(keys, options = {}, &block) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/cash/accessor.rb', line 26

def get(keys, options = {}, &block)
  case keys
  when Array
    fetch(keys, options, &block)
  else
    fetch(keys, options) do
      if block_given?
        add(keys, result = yield(keys))
        result
      end
    end
  end
end

#incr(key, delta = 1, ttl = 0) ⇒ Object



48
49
50
51
52
53
# File 'lib/cash/accessor.rb', line 48

def incr(key, delta = 1, ttl = 0)
  repository.incr(cache_key(key), delta) || begin
    repository.set(cache_key(key), (result = yield).to_s, ttl, true)
    result
  end
end

#set(key, value, options = {}) ⇒ Object



44
45
46
# File 'lib/cash/accessor.rb', line 44

def set(key, value, options = {})
  repository.set(cache_key(key), value, options[:ttl] || 0, options[:raw])
end