diff options
author | Yorick Peterse <yorickpeterse@gmail.com> | 2017-11-15 17:47:10 +0300 |
---|---|---|
committer | Yorick Peterse <yorickpeterse@gmail.com> | 2017-11-16 16:59:38 +0300 |
commit | 3e561736b2eb4866b75c57c01769586f058a2f8d (patch) | |
tree | 6e136d37d558b14bfbc2505f8b8f564fa96eab6f /app/services/base_count_service.rb | |
parent | 81e94ce1761b48b73be2a8d71938dfe934921e35 (diff) |
Cache the number of user SSH keys
By caching the number of personal SSH keys we reduce the number of
queries necessary on pages such as ProjectsController#show (which can
end up querying this data multiple times).
The cache is refreshed/flushed whenever an SSH key is added, removed, or
when a user is removed.
Diffstat (limited to 'app/services/base_count_service.rb')
-rw-r--r-- | app/services/base_count_service.rb | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/app/services/base_count_service.rb b/app/services/base_count_service.rb new file mode 100644 index 00000000000..99cc9a196e6 --- /dev/null +++ b/app/services/base_count_service.rb @@ -0,0 +1,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 |