Module: Card::ViewCache

Defined in:
lib/card/view_cache.rb

Constant Summary collapse

SIZE =
500
LIMIT =

reduce cache size to SIZE if LIMIT is reached

1000
CNT_KEY =
'view_cache_cnt'
FREQUENCY_KEY =
'view_cache_frequency'

Class Method Summary collapse

Class Method Details

.cacheObject



9
10
11
# File 'lib/card/view_cache.rb', line 9

def cache
  Card::Cache[Card::ViewCache]
end

.countObject



17
18
19
# File 'lib/card/view_cache.rb', line 17

def count
  cache.read(CNT_KEY) || 0
end

.fetch(format, view, args, &block) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/card/view_cache.rb', line 43

def fetch(format, view, args, &block)
  if !Card.config.view_cache || !format.view_caching? || !format.main? ||  (view != :open && view != :content) || format.class != HtmlFormat
    return block.call
  end

  roles = Card::Auth.current.all_roles.sort.join '_'
  key = "view_#{view}_#{format.card.key}_args_#{Card::Cache.obj_to_key(args)}_roles_#{roles}"

  if !cache.exist?(key)
    increment_cnt
    reduce_cache if count > LIMIT
  end

  update_frequency do |freq|
    freq[key] ||= 0
    freq[key] += 1
  end

  if Card.config.view_cache == 'debug'
    if cache.exist? key
      "fetched from view cache: #{cache.read key}"
    else
      "written to view cache: #{cache.fetch(key, &block)}"
    end
  else
    cache.fetch(key, &block)
  end
end

.increment_cntObject



13
14
15
# File 'lib/card/view_cache.rb', line 13

def increment_cnt
  cache.write(CNT_KEY, count+1)
end

.reduce_cacheObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/card/view_cache.rb', line 21

def reduce_cache
  update_frequency do |freq|
    cnts_with_key = freq.keys.map { |key| [freq[key], key] }
    index = 1
    SortedSet.new(cnts_with_key).each do |cnt, key|
      if index < (LIMIT - SIZE)
        cache.delete(key)
        freq.delete(key)
      else
        freq[key] = 0
      end
      index += 1
    end
  end
end

.reset(hard = false) ⇒ Object



72
73
74
# File 'lib/card/view_cache.rb', line 72

def reset hard=false
  cache.reset hard
end

.update_frequency {|freq| ... } ⇒ Object

Yields:

  • (freq)


37
38
39
40
41
# File 'lib/card/view_cache.rb', line 37

def update_frequency
  freq = cache.read(FREQUENCY_KEY) || {}
  yield(freq)
  cache.write(FREQUENCY_KEY, freq)
end