Skip to content

Commit

Permalink
Add logic for ranking the gems by download
Browse files Browse the repository at this point in the history
  • Loading branch information
juankuquintana committed May 21, 2023
1 parent 75540cb commit 5165fcf
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
22 changes: 22 additions & 0 deletions app/models/rubygem.rb
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,15 @@ def downloads
gem_download&.count || 0
end

def gem_rank
gem_ranking = update_gems_ranking

return gem_ranking[id] if gem_ranking.key?(id)

Rails.cache.delete("gems_ranking")
update_gems_ranking[id]
end

def most_recent_version
versions.most_recent
end
Expand Down Expand Up @@ -446,4 +455,17 @@ def bulk_reorder_versions
sanitized_query = ActiveRecord::Base.send(:sanitize_sql_array, update_query)
ActiveRecord::Base.connection.execute(sanitized_query)
end

def update_gems_ranking
Rails.cache.fetch("gems_ranking", expires_in: 24.hours) do
update_query = <<-SQL.squish
SELECT rubygem_id, row_number() OVER(ORDER BY count DESC) AS position
FROM gem_downloads
WHERE version_id = 0 AND rubygem_id <> 0
SQL
sanitized_query = ActiveRecord::Base.send(:sanitize_sql_array, [update_query])
pg_result = ActiveRecord::Base.connection.execute(sanitized_query)
pg_result.to_h { |row| [row["rubygem_id"], row["position"]] }
end
end
end
37 changes: 37 additions & 0 deletions test/models/rubygem_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1102,4 +1102,41 @@ class RubygemTest < ActiveSupport::TestCase
refute_predicate @version_three, :yanked?
end
end

context "#gem_rank" do
setup do
@rank_one = create(:rubygem, downloads: 5)
@rank_two = create(:rubygem, downloads: 1)

@dummy_rank = { @rank_one.id => 1, @rank_two.id => 2 }
end

should "write to cache" do
@rank_one.gem_rank

assert_equal Rails.cache.read("gems_ranking"), @dummy_rank
end

should "read from cache" do
@rank_two.gem_rank

GemDownload.increment(10, rubygem_id: @rank_two.id)

@rank_two.gem_rank

assert_equal Rails.cache.read("gems_ranking"), @dummy_rank
end

should "return the gem rank" do
assert_equal 1, @rank_one.gem_rank
end

should "update when rubygem not ranked" do
@rank_two.gem_rank

@rank_three = create(:rubygem, downloads: 3)

assert_equal(2, @rank_three.gem_rank)
end
end
end

0 comments on commit 5165fcf

Please sign in to comment.