Module: BipolarCache

Defined in:
lib/bipolar_cache.rb,
lib/bipolar_cache/version.rb,
lib/bipolar_cache/sequel/plugin_alpha.rb

Defined Under Namespace

Modules: Sequel Classes: Error

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.read!(**procs) ⇒ Object

It may read actual value, it may read cached value, or it may write actual value into cache! It depends on chance. Call it at your peril.

Parameters:

  • actual (Proc)

    callable to perform an operation (cacheable)

  • cached (Proc)

    callable to read cached value

  • chance (Proc(Object))

    callable to compute chance of cache hit

  • if (Proc)

    callable to enable/disable caching

  • rescue (Proc(StandardError))

    callable to be invoked on exception

  • update (Proc(Object))

    callable to update cached value

Returns:

  • (Object)


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/bipolar_cache.rb', line 22

def self.read!(**procs)
  return procs[:actual].call unless procs[:if].call

  cached_value = procs[:cached].call

  if procs[:chance].call(cached_value) > rand
    cached_value
  else
    actual_value = procs[:actual].call
    procs[:update].call(actual_value) if cached_value != actual_value

    actual_value
  end
rescue StandardError => e
  procs[:rescue].call(e) if procs[:rescue].is_a?(Proc)
end