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.



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

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



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

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)


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

def caching_enabled?
  Workbook.caching_enabled?
end

#fetch_cache(key, expires = nil) ⇒ Object



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

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
  return @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)



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

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)


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

def valid_cache_key?(key, expires=nil)
  cache_valid_from
  rv = (@cache[key] and (@cache[key][:inserted_at] > cache_valid_from) and (expires.nil? or @cache[key][:inserted_at] < expires)) ? true : false
  rv
end