Class: ViewModel::ActiveRecord::Cache::CacheableView::CacheClearer

Inherits:
Struct
  • Object
show all
Includes:
ViewModel::AfterTransactionRunner
Defined in:
lib/view_model/active_record/cache/cacheable_view.rb

Overview

Callback handler to participate in ActiveRecord::ConnectionAdapters

Transaction callbacks: invalidates a given cache member after the current transaction commits.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from ViewModel::AfterTransactionRunner

#add_to_transaction, #after_commit, #before_committed!, #committed!, #rolledback!, #trigger_transactional_callbacks?

Instance Attribute Details

#cacheObject

Returns the value of attribute cache

Returns:

  • (Object)

    the current value of cache



12
13
14
# File 'lib/view_model/active_record/cache/cacheable_view.rb', line 12

def cache
  @cache
end

#idObject

Returns the value of attribute id

Returns:

  • (Object)

    the current value of id



12
13
14
# File 'lib/view_model/active_record/cache/cacheable_view.rb', line 12

def id
  @id
end

Instance Method Details

#after_rollbackObject



25
26
27
# File 'lib/view_model/active_record/cache/cacheable_view.rb', line 25

def after_rollback
  cache.delete(id)
end

#before_commitObject

It’s important that we clear the cache before committing, because we rely on database locking to prevent cache race conditions. We require reading/refreshing the cache to obtain a FOR SHARE lock, which means that a reader must wait for a concurrent writer to commit before continuing to the cache. If the writer cleared the cache after commit, the reader could obtain old data before the clear, and then save the old data after it.



21
22
23
# File 'lib/view_model/active_record/cache/cacheable_view.rb', line 21

def before_commit
  cache.delete(id)
end

#connectionObject



29
30
31
# File 'lib/view_model/active_record/cache/cacheable_view.rb', line 29

def connection
  cache.viewmodel_class.model_class.connection
end