Skip to content

Instantly share code, notes, and snippets.

@wilkie
Forked from steveklabnik/fetch_gists.rb
Last active December 15, 2015 15:39
Show Gist options
  • Save wilkie/5283510 to your computer and use it in GitHub Desktop.
Save wilkie/5283510 to your computer and use it in GitHub Desktop.
require 'net/http'
require 'json'
# a simple wrapper to do an HTTP GET
def fetch_uri(uri, limit = 10)
uri = URI(uri)
request = Net::HTTP::Get.new(uri.request_uri)
http = Net::HTTP.new(uri.hostname, uri.port)
if uri.scheme == 'https'
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
end
response = http.request(request)
if response.is_a?(Net::HTTPRedirection) && limit > 0
location = response['location']
fetch_uri(location, limit - 1)
else
response
end
end
# GETs the URI and returns a Ruby hash.
def fetch_json(uri)
result = fetch_uri(uri)
JSON.load(result.body)
end
def parse_uri_template(uri, thing)
uri.gsub /\{(\/)?.*\}/, "\\1#{thing}"
end
# Let's begin!
json = fetch_json('https://api.github.com/')
# Could be cleaner!
gist_uri = parse_uri_template(json["gists_url"], "5283510")
gist_json = fetch_json(gist_uri)
gist_filename = gist_json["files"].keys.first
gist_raw_uri = gist_json["files"][gist_filename]["raw_url"]
gist = fetch_uri(gist_raw_uri)
# Quine!
puts gist.body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment