-
-
Save matugm/bee45bfe637f0abf8f29 to your computer and use it in GitHub Desktop.
API call with fallback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rest-client' | |
require 'securerandom' | |
module QRandom | |
MAX_NUMBER = 99999 | |
def self.next | |
api_url = 'http://qrng.anu.edu.au/API/jsonI.php?type=uint16&length=2' | |
RestClient.get(api_url) do |response, request, result, &block| | |
response.code == 200 ? parse_response(response) : fallback_number(response) | |
end | |
end | |
def self.parse_response(response) | |
json = JSON.parse(response) | |
if json["success"] == true && json["data"] | |
json["data"].inject(:+) % MAX_NUMBER || fallback_number | |
else | |
fallback_number | |
end | |
end | |
def self.fallback_number(response) | |
puts "--- Fallback triggered ---" | |
puts response.inspect | |
SecureRandom.random_number(MAX_NUMBER) | |
end | |
end | |
puts QRandom::next |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment