Class: CacheBack::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/cache_back/cache.rb

Defined Under Namespace

Classes: CachedModel

Instance Method Summary collapse

Constructor Details

#initializeCache

Returns a new instance of Cache.



3
4
5
# File 'lib/cache_back/cache.rb', line 3

def initialize
  reset!
end

Instance Method Details

#delete(*args) ⇒ Object



52
53
54
55
# File 'lib/cache_back/cache.rb', line 52

def delete(*args)
  @local_cache.delete(args[0])
  Rails.cache.delete(*args)
end

#delete_local(*keys) ⇒ Object



57
58
59
60
61
# File 'lib/cache_back/cache.rb', line 57

def delete_local(*keys)
  keys.each do |key|
    @local_cache.delete(key)
  end
end

#get_multi(keys) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/cache_back/cache.rb', line 20

def get_multi(keys)
  map = Hash[keys.zip(keys.map { |key| @local_cache[key] })]
  missing_keys = map.select { |key, value| value.nil? }.map(&:first)

  unless missing_keys.empty?
    if Rails.cache.respond_to?(:read_multi)
      missing_map = Rails.cache.read_multi(missing_keys)
      missing_map.each do |key, value|
        value = value.instanciate_model if value.is_a?(CachedModel)
        missing_map[key] = @local_cache[key] = value
      end
      map.merge!(missing_map)
    else
      missing_keys.each do |key|
        map[key] = read(key)
      end
    end
  end

  map
end

#read(*args) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/cache_back/cache.rb', line 7

def read(*args)
  result = @local_cache[args[0]] || Rails.cache.read(*args)
  if result.is_a?(CachedModel)
    result = result.instanciate_model
  elsif result.is_a?(Array)
    models = get_multi(result)
    result = result.map { |key| models[key]}
  end

  @local_cache[args[0]] = result if result
  result
end

#reset!Object



63
64
65
# File 'lib/cache_back/cache.rb', line 63

def reset!
  @local_cache = {}
end

#write(*args) ⇒ Object



42
43
44
45
46
47
48
49
50
# File 'lib/cache_back/cache.rb', line 42

def write(*args)
  @local_cache[args[0]] = args[1]

  if args[1].is_a?(ActiveRecord::Base)
    args[1] = CachedModel.new(args[1])
  end

  Rails.cache.write(*args)
end