Sha256: 5a48569baa8c0ed51abeb3f0deae0962788ebdeae26acd5d024870b4ec4aa96c
Contents?: true
Size: 1.53 KB
Versions: 1
Compression:
Stored size: 1.53 KB
Contents
# frozen_string_literal: true require "net/http" require "json" module GetXkcd # Class that exposes methods for fetching XKCD comic data class Comic # Get the json for the most recent xkcd comic def self.fetch_latest_issue_data uri = URI("https://xkcd.com/info.0.json") req = Net::HTTP::Get.new(uri) req["Accept"] = "application/json" res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(req) end JSON.parse(res.body) end # Get the json for the xkcd comic of a specific number def self.fetch_random_issue_data uri = URI("https://xkcd.com/#{generate_random_issue_number}/info.0.json") req = Net::HTTP::Get.new(uri) req["Accept"] = "application/json" res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(req) end JSON.parse(res.body) end # Generate a random number up to the latest issue number (excluding 404) def self.generate_random_issue_number latest_issue_number = fetch_latest_issue_data["num"] generate_random_number_excluding_404(latest_issue_number) end # Generate a random number from 1 up to input argument (excluding 404) def self.generate_random_number_excluding_404(max) number = rand(max) + 1 return number unless number == 404 generate_random_number_excluding_404(max) end private_class_method :generate_random_issue_number, :generate_random_number_excluding_404 end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
get_xkcd-0.1.0 | lib/get_xkcd/comic.rb |