Class: Card::Cache::Temporary

Inherits:
Object
  • Object
show all
Defined in:
lib/card/cache/temporary.rb

Overview

The Temporary cache is intended for a single request, script, migration, etc. It allows you to alter a card and then retrieve the card with those alterations intact without saving those changes to the database.

In practice, it’s a set of Cache-like methods for using a simple Hash.

Unlike the Shared cache, the Temporary cache can handle objects with singleton classes.

Constant Summary collapse

MAX_KEYS =
10_000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass) ⇒ Temporary

Returns a new instance of Temporary.



17
18
19
20
21
# File 'lib/card/cache/temporary.rb', line 17

def initialize klass
  @klass = klass
  @store = {}
  @reps = 0
end

Instance Attribute Details

#storeObject (readonly)

Returns the value of attribute store.



15
16
17
# File 'lib/card/cache/temporary.rb', line 15

def store
  @store
end

Instance Method Details

#delete(key) ⇒ Object

Parameters:

  • key (String)


55
56
57
# File 'lib/card/cache/temporary.rb', line 55

def delete key
  @store.delete key
end

#dumpObject



59
60
61
62
63
# File 'lib/card/cache/temporary.rb', line 59

def dump
  @store.each do |k, v|
    p "#{k} --> #{v.inspect[0..30]}"
  end
end

#exist?(key) ⇒ Boolean

Parameters:

  • key (String)

Returns:

  • (Boolean)


71
72
73
# File 'lib/card/cache/temporary.rb', line 71

def exist? key
  @store.key? key
end

#fetch(key) ⇒ Object

Parameters:

  • key (String)


39
40
41
42
# File 'lib/card/cache/temporary.rb', line 39

def fetch key
  # read(key) || write(key, yield)
  exist?(key) ? read(key) : write(key, yield)
end

#fetch_multi(keys) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/card/cache/temporary.rb', line 44

def fetch_multi keys
  @store.slice(*keys).tap do |found|
    missing = keys - found.keys
    if (newfound = missing.present? && yield(missing))
      found.merge! newfound
      newfound.each { |key, value| write key, value }
    end
  end
end

#read(key) ⇒ Object

Parameters:

  • key (String)


24
25
26
# File 'lib/card/cache/temporary.rb', line 24

def read key
  @store[key]
end

#resetObject



65
66
67
68
# File 'lib/card/cache/temporary.rb', line 65

def reset
  @reps = 0
  @store = {}
end

#write(key, value, callback: true) ⇒ Object

Parameters:

  • key (String)


29
30
31
32
33
34
35
36
# File 'lib/card/cache/temporary.rb', line 29

def write key, value, callback: true
  within_key_counts do
    @store[key] = value.tap do
      @reps += 1
      @klass.try :after_write_to_temp_cache, value if callback
    end
  end
end