Module: Cash::Accessor::ClassMethods

Defined in:
lib/cash/accessor.rb

Constant Summary collapse

MAX_KEY_SIZE =
250

Instance Method Summary collapse

Instance Method Details

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



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

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



73
74
75
76
77
78
79
# File 'lib/cash/accessor.rb', line 73

def cache_key(key)
  s = "#{name}:#{cache_config.version}/#{key.to_s.gsub(' ', '+')}"
  if s.size >= MAX_KEY_SIZE
    s = Digest::MD5.hexdigest(s)
  end
  s
end

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



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

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



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

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

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



16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/cash/accessor.rb', line 16

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



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/cash/accessor.rb', line 31

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



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

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



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

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