Class: Para::Cache::DatabaseStore

Inherits:
ActiveSupport::Cache::Store
  • Object
show all
Defined in:
lib/para/cache/database_store.rb

Instance Method Summary collapse

Instance Method Details

#clearObject



19
20
21
# File 'lib/para/cache/database_store.rb', line 19

def clear
  Item.delete_all
end

#delete_entry(key, options) ⇒ Object



23
24
25
# File 'lib/para/cache/database_store.rb', line 23

def delete_entry(key, options)
  Item.delete_all(key: key)
end

#read_entry(key, options = {}) ⇒ Object



27
28
29
# File 'lib/para/cache/database_store.rb', line 27

def read_entry(key, options={})
  RequestStore.store[cache_key_for(key)] ||= Item.find_by(key: key)
end

#write_entry(key, entry, options) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/para/cache/database_store.rb', line 31

def write_entry(key, entry, options)
  RequestStore.store[cache_key_for(key)] ||= Item.where(key: key).first_or_initialize
  item = RequestStore.store[cache_key_for(key)]

  options = options.clone.symbolize_keys

  item.value = entry.value
  item.expires_at = options[:expires_in].try(:since)

  # Save chace item in its own thread, to get a clean 
  # ActiveRecord::Base.connection.
  #
  # It allows cache to be saved inside transactions but without waiting 
  # transactions to be committed to commit chache changes.
  # 
  # This is needed for checking progress of long running tasks, like 
  # imports, that use the cache inside transactions but need other 
  # processes to get their state in real time.
  #
  Thread.new do
    item.save!
  end.join

  # Ensure cached item in RequestStore is up to date
  RequestStore.store[cache_key_for(key)] = item
rescue ActiveRecord::RecordNotUnique
ensure
  clear_expired_keys
end