From d4d0740e24315e7071f90b3744377b3ca3b5816a Mon Sep 17 00:00:00 2001 From: Andreas Brandl Date: Fri, 23 Feb 2018 20:56:43 +0100 Subject: [PATCH] Cache project/user combinations. --- app/models/user_contributed_projects.rb | 22 ++++++++++++++++--- spec/models/user_contributed_projects_spec.rb | 7 +++--- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/app/models/user_contributed_projects.rb b/app/models/user_contributed_projects.rb index 846d77f3c69..e051e75af1d 100644 --- a/app/models/user_contributed_projects.rb +++ b/app/models/user_contributed_projects.rb @@ -5,9 +5,25 @@ class UserContributedProjects < ActiveRecord::Base validates :project, presence: true validates :user, presence: true + CACHE_EXPIRY_TIME = 1.day + def self.track(event) - find_or_create_by!(project: event.project, user: event.author) - rescue ActiveRecord::RecordNotUnique - retry + attributes = {project_id: event.project_id, user_id: event.author_id} + + cached_exists?(attributes) do + begin + find_or_create_by!(attributes) + true # not caching the whole record here for now + rescue ActiveRecord::RecordNotUnique + retry + end + end + end + + private + + def self.cached_exists?(project_id:, user_id:, &block) + cache_key = "user_contributed_projects:#{project_id}:#{user_id}" + Rails.cache.fetch(cache_key, expires_in: CACHE_EXPIRY_TIME, &block) end end diff --git a/spec/models/user_contributed_projects_spec.rb b/spec/models/user_contributed_projects_spec.rb index 5b8c61750b3..b0a10ca59ab 100644 --- a/spec/models/user_contributed_projects_spec.rb +++ b/spec/models/user_contributed_projects_spec.rb @@ -12,16 +12,17 @@ describe UserContributedProjects do it 'creates a record' do expect { subject }.to change { UserContributedProjects.count }.from(0).to(1) end - end end it 'sets project accordingly' do - expect(subject.project).to eq(event.project) + subject + expect(UserContributedProjects.first.project).to eq(event.project) end it 'sets user accordingly' do - expect(subject.user).to eq(event.author) + subject + expect(UserContributedProjects.first.user).to eq(event.author) end it 'only creates a record once per user/project' do