module DbMemoize::Model

Public Instance Methods

memoize_values(values) click to toggle source

Used to set multiple memoized values in one go.

Example:

product.memoize_values full_title: "my full title",
                       autocomplete_info: "my autocomplete_info"

This sets the “full_title” and “autocomplete_info” values of the product.

# File lib/db_memoize/model.rb, line 36
def memoize_values(values)
  values.each do |name, value|
    create_memoized_value(name, value)
  end
end
memoized_value(method_name) click to toggle source
# File lib/db_memoize/model.rb, line 7
def memoized_value(method_name)
  memoizable = !changed? && persisted?
  return send("#{method_name}_without_memoize") unless memoizable

  memoized_value = find_memoized_value(method_name)

  if memoized_value
    memoized_value.value
  else
    value = send("#{method_name}_without_memoize")
    create_memoized_value(method_name, value)
    value
  end
end
unmemoize(method_name = :all) click to toggle source
# File lib/db_memoize/model.rb, line 22
def unmemoize(method_name = :all)
  self.class.unmemoize id, method_name
end

Private Instance Methods

create_memoized_value(method_name, value) click to toggle source
# File lib/db_memoize/model.rb, line 44
def create_memoized_value(method_name, value)
  self.class.transaction do
    ::DbMemoize::Value.fast_create self.class.table_name, id, method_name, value
    @association_cache.delete :memoized_values
    value
  end
end
find_memoized_value(method_name) click to toggle source
# File lib/db_memoize/model.rb, line 52
def find_memoized_value(method_name)
  method_name = method_name.to_s

  # In order to prevent database level deadlocks we don't manage any unique
  # index on memoized values. This can result in duplicate matching memoized
  # values.
  #
  # It is important to always return the freshest value. To make sure this
  # happens the \a memoized_values association is ordered by its creation
  # time (via "created_at DESC"), which lets us just return the first matching
  # entry here.
  memoized_values.detect do |rec|
    rec.method_name == method_name
  end
end