aef9f1eb94
The number of forks of a project doesn't change very frequently and running a COUNT(*) every time this information is requested can be quite expensive. We also end up running such a COUNT(*) query at least twice on the homepage of a project. By caching this data and refreshing it when necessary we can reduce project homepage loading times by around 60 milliseconds (based on the timings of https://gitlab.com/gitlab-org/gitlab-ce).
30 lines
560 B
Ruby
30 lines
560 B
Ruby
module Projects
|
|
# Service class for getting and caching the number of forks of a project.
|
|
class ForksCountService
|
|
def initialize(project)
|
|
@project = project
|
|
end
|
|
|
|
def count
|
|
Rails.cache.fetch(cache_key) { uncached_count }
|
|
end
|
|
|
|
def refresh_cache
|
|
Rails.cache.write(cache_key, uncached_count)
|
|
end
|
|
|
|
def delete_cache
|
|
Rails.cache.delete(cache_key)
|
|
end
|
|
|
|
private
|
|
|
|
def uncached_count
|
|
@project.forks.count
|
|
end
|
|
|
|
def cache_key
|
|
['projects', @project.id, 'forks_count']
|
|
end
|
|
end
|
|
end
|