2018-07-05 06:18:17 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-11-15 09:47:10 -05:00
|
|
|
# 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
|
2017-11-30 17:23:07 -05:00
|
|
|
Rails.cache.fetch(cache_key, cache_options) { uncached_count }.to_i
|
2017-11-15 09:47:10 -05:00
|
|
|
end
|
|
|
|
|
2017-11-24 11:37:02 -05:00
|
|
|
def count_stored?
|
|
|
|
Rails.cache.read(cache_key).present?
|
|
|
|
end
|
|
|
|
|
2017-11-24 07:20:52 -05:00
|
|
|
def refresh_cache(&block)
|
2018-06-15 13:32:37 -04:00
|
|
|
update_cache_for_key(cache_key, &block)
|
2017-11-15 09:47:10 -05:00
|
|
|
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
|
2019-08-27 16:50:26 -04:00
|
|
|
raise NotImplementedError, 'cache_key must be implemented and return a String, Array, or Hash'
|
2017-11-15 09:47:10 -05:00
|
|
|
end
|
2017-11-30 17:23:07 -05:00
|
|
|
|
|
|
|
# subclasses can override to add any specific options, such as
|
|
|
|
# super.merge({ expires_in: 5.minutes })
|
|
|
|
def cache_options
|
|
|
|
{ raw: raw? }
|
|
|
|
end
|
2018-06-15 13:32:37 -04:00
|
|
|
|
|
|
|
def update_cache_for_key(key, &block)
|
|
|
|
Rails.cache.write(key, block_given? ? yield : uncached_count, raw: raw?)
|
|
|
|
end
|
2017-11-15 09:47:10 -05:00
|
|
|
end
|