summaryrefslogtreecommitdiff
path: root/app/services/base_count_service.rb
blob: 99cc9a196e631062531489cd2c5598358b9990b0 (plain)
1
2
3
4
5
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
# Base class for services that count a single resource such as the number of
# issues for a project.
class BaseCountService
  def relation_for_count
    raise(
      NotImplementedError,
      '"relation_for_count" must be implemented and return an ActiveRecord::Relation'
    )
  end

  def count
    Rails.cache.fetch(cache_key, raw: raw?) { uncached_count }.to_i
  end

  def refresh_cache
    Rails.cache.write(cache_key, uncached_count, raw: raw?)
  end

  def uncached_count
    relation_for_count.count
  end

  def delete_cache
    Rails.cache.delete(cache_key)
  end

  def raw?
    false
  end

  def cache_key
    raise NotImplementedError, 'cache_key must be implemented and return a String'
  end
end