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
43
44
# File 'lib/cash/accessor.rb', line 40

def add(key, value, options = {})
  if repository.add(cache_key(key), value, options[:ttl] || 0, options[:raw]) == "NOT_STORED\r\n"
    yield
  end
end

#cache_key(key) ⇒ Object



68
69
70
# File 'lib/cash/accessor.rb', line 68

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

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



57
58
59
60
61
62
# File 'lib/cash/accessor.rb', line 57

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

#expire(key) ⇒ Object



64
65
66
# File 'lib/cash/accessor.rb', line 64

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!(missed_keys.zip(Array(missed_values)).to_hash)
    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), options)
        result
      end
    end
  end
end

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



50
51
52
53
54
55
# File 'lib/cash/accessor.rb', line 50

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

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



46
47
48
# File 'lib/cash/accessor.rb', line 46

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