Commit d4d0740e authored by Andreas Brandl's avatar Andreas Brandl

Cache project/user combinations.

parent ebcf3c73
......@@ -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
......@@ -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
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment