Cache project/user combinations.

This commit is contained in:
Andreas Brandl 2018-02-23 20:56:43 +01:00
parent ebcf3c73bd
commit d4d0740e24
2 changed files with 23 additions and 6 deletions

View File

@ -5,9 +5,25 @@ class UserContributedProjects < ActiveRecord::Base
validates :project, presence: true validates :project, presence: true
validates :user, presence: true validates :user, presence: true
CACHE_EXPIRY_TIME = 1.day
def self.track(event) def self.track(event)
find_or_create_by!(project: event.project, user: event.author) attributes = {project_id: event.project_id, user_id: event.author_id}
rescue ActiveRecord::RecordNotUnique
retry 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
end end

View File

@ -12,16 +12,17 @@ describe UserContributedProjects do
it 'creates a record' do it 'creates a record' do
expect { subject }.to change { UserContributedProjects.count }.from(0).to(1) expect { subject }.to change { UserContributedProjects.count }.from(0).to(1)
end end
end end
end end
it 'sets project accordingly' do it 'sets project accordingly' do
expect(subject.project).to eq(event.project) subject
expect(UserContributedProjects.first.project).to eq(event.project)
end end
it 'sets user accordingly' do it 'sets user accordingly' do
expect(subject.user).to eq(event.author) subject
expect(UserContributedProjects.first.user).to eq(event.author)
end end
it 'only creates a record once per user/project' do it 'only creates a record once per user/project' do