Class: SmartCollection::CacheManager::Table

Inherits:
SmartCollection::CacheManager show all
Defined in:
lib/smart_collection/cache_manager/table.rb

Instance Method Summary collapse

Methods inherited from SmartCollection::CacheManager

determine_class, #expires_in

Constructor Details

#initialize(model:, config:) ⇒ Table

Returns a new instance of Table.



5
6
7
8
9
# File 'lib/smart_collection/cache_manager/table.rb', line 5

def initialize model:, config:
  super

  define_cache_association_for model
end

Instance Method Details

#cache_exists?(owner) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/smart_collection/cache_manager/table.rb', line 38

def cache_exists? owner
  owner.cache_expires_at && owner.cache_expires_at > Time.now
end

#define_cache_association_for(model) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/smart_collection/cache_manager/table.rb', line 11

def define_cache_association_for model
  config = @config
  cached_item_model = nil
  model.class_eval do
    cached_item_model = Class.new ActiveRecord::Base do
      self.table_name = 'smart_collection_cached_items'
      belongs_to config.item_name, class_name: config.item_class_name, foreign_key: :item_id
    end
    const_set("CachedItem", cached_item_model)

    has_many :cached_items, class_name: cached_item_model.name, foreign_key: :collection_id
    has_many "cached_#{config.items_name}".to_sym, class_name: config.item_class_name, through: :cached_items, source: config.item_name
  end
  @cache_model = cached_item_model
end

#read_scope(owner) ⇒ Object



33
34
35
36
# File 'lib/smart_collection/cache_manager/table.rb', line 33

def read_scope owner
  cache_association = owner.association("cached_#{@config.items_name}")
  cache_association.scope
end

#update(owner) ⇒ Object



27
28
29
30
31
# File 'lib/smart_collection/cache_manager/table.rb', line 27

def update owner
  @cache_model.where(collection_id: owner.id).delete_all
  @cache_model.connection.execute "INSERT INTO #{@cache_model.table_name} (collection_id, item_id) #{owner.smart_collection_mixin.uncached_scope(owner).select(owner.id, :id).to_sql}"
  owner.update_column(:cache_expires_at, Time.now + expires_in)
end