Module: Counter::CounterCache::ClassMethods

Defined in:
app/models/counter.rb

Instance Method Summary collapse

Instance Method Details

#define_counter_cache(attr_name, &block) ⇒ Object



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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'app/models/counter.rb', line 35

def define_counter_cache(attr_name, &block)
  update_counter = "update_#{attr_name}".to_sym
  after_commit update_counter, on: :update

  destroy_counter = "destroy_#{attr_name}".to_sym
  after_commit destroy_counter, on: :destroy

  define_method attr_name.to_sym do
    cache_key = "#{self.class}:#{id}:#{attr_name}"

    value = Counter.fetch_value_by_key(cache_key)
    if value.nil?
      counter = Counter.find_by key: cache_key
      value = block.call(self)
      if counter.nil?
        CounterOperationWorker.perform_async('create', cache_key, value)
      else
        CounterOperationWorker.perform_async('update', counter.id, value)
      end
    end
    value
  rescue => error
    APMErrorHandler.report error
    value
  end

  define_method update_counter do
    cache_key = "#{self.class}:#{id}:#{attr_name}"
    counter = Counter.find_by key: cache_key
    if counter&.persisted?
      value = block.call(self)
      CounterOperationWorker.perform_async('update', counter.id, value)
    end
    true
  end

  define_method destroy_counter do
    cache_key = "#{self.class}:#{id}:#{attr_name}"
    counter = Counter.find_by key: cache_key
    CounterOperationWorker.perform_async('destroy', counter.id) if counter&.persisted?
    true
  end
end