Skip to content

Instantly share code, notes, and snippets.

@kevinlinxc
Last active August 15, 2022 22:55
Show Gist options
  • Save kevinlinxc/566eaf3712785371e4386dea0eec4e77 to your computer and use it in GitHub Desktop.
Save kevinlinxc/566eaf3712785371e4386dea0eec4e77 to your computer and use it in GitHub Desktop.
Get download count for a Ruby gem using the RubyGems.org API
def get_downloads(gem_name, version=nil)
# query rubygems api for total downloads of gem_name for the given version
# return integer of downloads
# if version is nil, return total downloads of the latest version
# requires uri, net/http, and json
if version == nil
uri = URI("https://rubygems.org/api/v1/gems/#{gem_name}.json")
response = Net::HTTP.get_response(uri)
res = JSON.parse(response.body) if response.is_a?(Net::HTTPSuccess)
res["downloads"]
else
uri = URI("https://rubygems.org/api/v1/downloads/#{gem_name}-#{version}.json")
response = Net::HTTP.get_response(uri)
res = JSON.parse(response.body) if response.is_a?(Net::HTTPSuccess)
res["total_downloads"]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment