Module: Workbook::Modules::Cache

Included in:
Row
Defined in:
lib/workbook/modules/cache.rb

Overview

Adds simple caching

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#debug_cacheObject

Returns the value of attribute debug_cache.



8
9
10
# File 'lib/workbook/modules/cache.rb', line 8

def debug_cache
  @debug_cache
end

Instance Method Details

#cache_valid_fromTime

Return valid cache time, if caching is enabled, otherwise calls #invalidate_cache!

Returns:

  • (Time)

    Timestamp after which cache is valid



18
19
20
21
22
23
24
25
# File 'lib/workbook/modules/cache.rb', line 18

def cache_valid_from
  if caching_enabled?
    @cache_valid_from ||= Time.now
  else
    invalidate_cache!
  end
  @cache_valid_from
end

#caching_enabled?Boolean

Caching enabled?

Returns:

  • (Boolean)


12
13
14
# File 'lib/workbook/modules/cache.rb', line 12

def caching_enabled?
  Workbook.caching_enabled?
end

#fetch_cache(key, expires = nil) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/workbook/modules/cache.rb', line 40

def fetch_cache(key, expires = nil)
  @cache ||= {}
  if valid_cache_key?(key, expires)
    return @cache[key][:value]
  else
    @cache[key] = {
      value: yield,
      inserted_at: Time.now
    }
  end
  @cache[key][:value]
end

#invalidate_cache!Time

Invalidate all caches on this instance, and reset

Returns:

  • (Time)

    Timestamp after which cache is valid (=current time, hence everything stored before is invalid)



29
30
31
# File 'lib/workbook/modules/cache.rb', line 29

def invalidate_cache!
  @cache_valid_from = Time.now
end

#valid_cache_key?(key, expires = nil) ⇒ Boolean

Check if currently stored key is available and still valid

Returns:

  • (Boolean)


35
36
37
38
# File 'lib/workbook/modules/cache.rb', line 35

def valid_cache_key?(key, expires = nil)
  cache_valid_from
  @cache[key] && (@cache[key][:inserted_at] > cache_valid_from) && (expires.nil? || (@cache[key][:inserted_at] < expires))
end