Module: DbMemoize::Model

Extended by:
ActiveSupport::Concern
Defined in:
lib/db_memoize/model.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#memoized_custom_keyObject



36
37
38
# File 'lib/db_memoize/model.rb', line 36

def memoized_custom_key
  ::DbMemoize.default_custom_key
end

#memoized_value(method_name, args) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/db_memoize/model.rb', line 5

def memoized_value(method_name, args)
  if changed? || !persisted?
    return send("#{method_name}_without_memoize", *args)
  end

  value         = nil
  args_hash     = ::Digest::MD5.hexdigest(Marshal.dump(args))
  cached_value  = find_memoized_value(method_name, args_hash)

  if cached_value
    log(method_name, 'cache hit')
    value = Marshal.load(cached_value.value)
  else
    time = ::Benchmark.realtime do
      value = send("#{method_name}_without_memoize", *args)
    end
    # dear rubocop, we can't use `format` here, since some of our models have a
    # `format` method themselves.
    # rubocop:disable Style/FormatString
    log(method_name, "cache miss. took #{sprintf('%.2f', time * 1_000)}ms")
    # rubocop:enable Style/FormatString
    create_memoized_value(method_name, args_hash, value)
  end

  value
end

#unmemoize(method_name = :all) ⇒ Object



32
33
34
# File 'lib/db_memoize/model.rb', line 32

def unmemoize(method_name = :all)
  self.class.unmemoize(self, method_name)
end