Skip to content

Instantly share code, notes, and snippets.

@matugm
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matugm/bee45bfe637f0abf8f29 to your computer and use it in GitHub Desktop.
Save matugm/bee45bfe637f0abf8f29 to your computer and use it in GitHub Desktop.
API call with fallback
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