Class: CacheAdvance::NamedCache

Inherits:
Object
  • Object
show all
Defined in:
lib/cache_advance/named_cache.rb

Constant Summary collapse

ENABLED_CHECK_INTERVAL =
60

Instance Method Summary collapse

Constructor Details

#initialize(name, params, cache_set, store) ⇒ NamedCache

Returns a new instance of NamedCache.



6
7
8
9
10
11
12
13
14
# File 'lib/cache_advance/named_cache.rb', line 6

def initialize(name, params, cache_set, store)
  @name = name.to_s
  @params = params
  @cache_set = cache_set
  @store = store
  @cached_key_list = CachedKeyList.new(@store, "#{@name}/STORED_CACHES", expiration_time)
  @enabled_check_time = Time.now + ENABLED_CHECK_INTERVAL
  @enabled = nil
end

Instance Method Details

#all_cached_keysObject



45
46
47
# File 'lib/cache_advance/named_cache.rb', line 45

def all_cached_keys
  @cached_key_list.all_keys
end

#enabled=(state) ⇒ Object



57
58
59
60
# File 'lib/cache_advance/named_cache.rb', line 57

def enabled=(state)
  @enabled = !!state
  @store.set(enabled_key, @enabled)
end

#enabled?Boolean

Returns:

  • (Boolean)


62
63
64
65
66
67
68
# File 'lib/cache_advance/named_cache.rb', line 62

def enabled?
  if @enabled.nil? || Time.now >= @enabled_check_time
    @enabled = [nil, true].include?(read_from_store(enabled_key))
    @enabled_check_time = Time.now + ENABLED_CHECK_INTERVAL
  end
  @enabled
end

#expiration_typesObject



49
50
51
# File 'lib/cache_advance/named_cache.rb', line 49

def expiration_types
  Array(@params[:expiration_types])
end

#expire_allObject



41
42
43
# File 'lib/cache_advance/named_cache.rb', line 41

def expire_all
  delete_all_from_store
end

#expire_for(type) ⇒ Object



35
36
37
38
39
# File 'lib/cache_advance/named_cache.rb', line 35

def expire_for(type)
  if expiration_types.include?(type)
    expire_all
  end
end

#titleObject



53
54
55
# File 'lib/cache_advance/named_cache.rb', line 53

def title
  @params[:title] || @name.to_s
end

#value_for(request, options, &block) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/cache_advance/named_cache.rb', line 16

def value_for(request, options, &block)
  return block.call unless enabled?
  
  key = key_for(request, options[:key])
  
  if (value = read_from_store(key))
    each_plugin { |p| p.send('after_read', @name, key, request, value) if p.respond_to?('after_read') }
    return value
  end
  
  each_plugin { |p| p.send('before_render', @name, key, request) if p.respond_to?('before_render') }
  result = block.call
  each_plugin { |p| p.send('after_render', @name, key, request, result) if p.respond_to?('after_render') }
  each_plugin { |p| p.send('before_write', @name, key, request, result) if p.respond_to?('before_write') }
  write_to_store(key, result)
  each_plugin { |p| p.send('after_write', @name, key, request, result) if p.respond_to?('after_write') }      
  result
end