class Card::Cache::Temporary
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.
Constants
- MAX_KEYS
Attributes
Public Class Methods
Source
# File lib/card/cache/temporary.rb, line 17 def initialize klass @klass = klass @store = {} @reps = 0 end
Public Instance Methods
Source
# File lib/card/cache/temporary.rb, line 55 def delete key @store.delete key end
@param key [String]
Source
# File lib/card/cache/temporary.rb, line 59 def dump @store.each do |k, v| p "#{k} --> #{v.inspect[0..30]}" end end
Source
# File lib/card/cache/temporary.rb, line 71 def exist? key @store.key? key end
@param key [String]
Source
# File lib/card/cache/temporary.rb, line 39 def fetch key # read(key) || write(key, yield) exist?(key) ? read(key) : write(key, yield) end
@param key [String]
Source
# 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
Source
# File lib/card/cache/temporary.rb, line 24 def read key @store[key] end
@param key [String]
Source
# 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
@param key [String]
Private Instance Methods
Source
# File lib/card/cache/temporary.rb, line 80 def within_key_counts if @reps >= MAX_KEYS && (@reps = @store.size) > MAX_KEYS Rails.logger.info "RESETTING temporary #{@klass} cache. " \ "MAX_KEYS (#{MAX_KEYS}) exceeded" reset end yield end
enforces MAX_KEYS
. The @reps count increments with each write but may overestimate the store size, because of multiple writes to the same key. (but this approach avoids recounting each time)