Module: Devise::Rownd::Caching

Defined in:
lib/devise/rownd/caching.rb

Class Method Summary collapse

Class Method Details

.fetch(cache_key, ttl) ⇒ Object



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
31
32
33
34
35
36
37
# File 'lib/devise/rownd/caching.rb', line 6

def fetch(cache_key, ttl)
  cache_val = Rails.cache.read(cache_key)

  # If there's nothing in the cache, yield the value and write it to cache
  if cache_val.nil?
    Devise::Rownd::Log.debug("cache: key not found '#{cache_key}'")
    return_value = yield
    if return_value
      Devise::Rownd::Log.debug("cache: updating cache. '#{cache_key}' value: #{return_value}")
      Rails.cache.write(cache_key, [return_value, Time.now]) if return_value
    end
  else
    Devise::Rownd::Log.debug("cache: key found: '#{cache_key}'")
    return_value = cache_val[0]
    last_fetch_time = cache_val[1]

    # Start a new thread to update the cached value if the TTL is exceeded
    Async do
      begin
        if Time.now - last_fetch_time > ttl
          new_value = yield
          Devise::Rownd::Log.debug("cache: updating cache. '#{cache_key}' value: #{new_value}")
          Rails.cache.write(cache_key, [new_value, Time.now]) if new_value
        end
      rescue StandardError => e
        Devise::Rownd::Log.error("cache: failed updating cache: #{e.message}")
      end
    end
  end

  return_value
end