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

store[R]

Public Class Methods

new(klass) click to toggle source
# File lib/card/cache/temporary.rb, line 17
def initialize klass
  @klass = klass
  @store = {}
  @reps = 0
end

Public Instance Methods

delete(key) click to toggle source

@param key [String]

# File lib/card/cache/temporary.rb, line 55
def delete key
  @store.delete key
end
dump() click to toggle source
# 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) click to toggle source

@param key [String]

# File lib/card/cache/temporary.rb, line 71
def exist? key
  @store.key? key
end
fetch(key) { || ... } click to toggle source

@param key [String]

# 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) { |missing| ... } click to toggle 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
read(key) click to toggle source

@param key [String]

# File lib/card/cache/temporary.rb, line 24
def read key
  @store[key]
end
reset() click to toggle source
# File lib/card/cache/temporary.rb, line 65
def reset
  @reps = 0
  @store = {}
end
write(key, value, callback: true) click to toggle source

@param key [String]

# 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

Private Instance Methods

within_key_counts() { || ... } click to toggle source

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)

# 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