class GemLookup::Requests

Constants

TIMEOUT_THRESHOLD

@return [Numeric] the seconds to wait before a response is considered timed out.

Public Class Methods

new(batch:, json: nil) click to toggle source
# File lib/gem_lookup/requests.rb, line 11
def initialize(batch:, json: nil)
  @batch = batch
  @json = json || { gems: [] }
end

Public Instance Methods

process() click to toggle source
# File lib/gem_lookup/requests.rb, line 16
def process
  Typhoeus::Hydra.hydra.tap do |hydra|
    populate_requests hydra: hydra, batch: @batch
  end.run

  @json
end

Private Instance Methods

api_url(gem_name:) click to toggle source
# File lib/gem_lookup/requests.rb, line 65
def api_url(gem_name:)
  "https://rubygems.org/api/v1/gems/#{gem_name}.json"
end
build_request(gem_name:) click to toggle source

rubocop:disable Layout/LineLength

# File lib/gem_lookup/requests.rb, line 33
def build_request(gem_name:)
  url = api_url gem_name: gem_name
  Typhoeus::Request.new(url, accept_encoding: 'gzip', timeout: TIMEOUT_THRESHOLD).tap do |request|
    request.on_complete do |response|
      if response.success?
        handle_successful_response json: JSON.parse(response.body, symbolize_names: true)
      elsif response.timed_out?
        handle_timed_out_response gem_name: gem_name
      else
        handle_failed_response gem_name: gem_name
      end
    end
  end
end
handle_failed_response(gem_name:) click to toggle source
# File lib/gem_lookup/requests.rb, line 60
def handle_failed_response(gem_name:)
  json = { name: gem_name, exists: false, timeout: false }
  @json[:gems].push json
end
handle_successful_response(json:) click to toggle source

rubocop:enable Layout/LineLength

# File lib/gem_lookup/requests.rb, line 49
def handle_successful_response(json:)
  json[:exists] = true
  json[:timeout] = false
  @json[:gems].push json
end
handle_timed_out_response(gem_name:) click to toggle source
# File lib/gem_lookup/requests.rb, line 55
def handle_timed_out_response(gem_name:)
  json = { name: gem_name, exists: false, timeout: true }
  @json[:gems].push json
end
populate_requests(hydra:, batch:) click to toggle source
# File lib/gem_lookup/requests.rb, line 26
def populate_requests(hydra:, batch:)
  batch.each do |gem_name|
    hydra.queue build_request gem_name: gem_name
  end
end