module Knuckles::Stages::Writer

After un-cached models have been serialized they are ready to be cached for future retrieval. Each fully serialized model is written to the cache in a single `write_multi` operation if available (using Readthis, for example). Only previously un-cached data will be written to the cache, making the writer a no-op when all of the data was cached initially.

Public Instance Methods

call(objects, _options) click to toggle source

Write all serialized, but previously un-cached, data to the cache.

@param [Enumerable] objects A collection of hashes to be serialized,

each hash must have they keys `:key`, `:result`, and `:cached?`.

@param [Hash] _options Options aren't used, but are accepted

to maintain a consistent interface

@return The original enumerable is returned unchanged

# File lib/knuckles/stages/writer.rb, line 21
def call(objects, _options)
  if cache.respond_to?(:write_multi)
    write_multi(objects)
  else
    write_each(objects)
  end

  objects
end

Private Instance Methods

cache() click to toggle source
# File lib/knuckles/stages/writer.rb, line 33
def cache
  Knuckles.cache
end
write_each(objects) click to toggle source
# File lib/knuckles/stages/writer.rb, line 37
def write_each(objects)
  objects.each do |hash|
    cache.write(hash[:key], hash[:result]) unless hash[:cached?]
  end
end
write_multi(objects) click to toggle source
# File lib/knuckles/stages/writer.rb, line 43
def write_multi(objects)
  writable = objects.each_with_object({}) do |hash, memo|
    next if hash[:cached?]

    memo[hash[:key]] = hash[:result]
  end

  cache.write_multi(writable) if writable.any?
end