Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env ruby
# coding: utf-8
require 'net/http'
require 'json'
# a simple wrapper to do an HTTPS GET
def fetch_uri(url)
STDERR.puts "GET #{url}" if ENV['VERBOSE']
uri = URI(url)
response = Net::HTTP.new(uri.host, uri.port).tap { |http| http.use_ssl = true }.request(Net::HTTP::Get.new(uri.request_uri))
STDERR.puts "⇣ #{response.inspect}" if ENV['VERBOSE']
response
end
# GETs the URI and returns a Ruby hash.
def fetch_json(uri)
result = fetch_uri(uri)
JSON.load(result.body)
end
# Gets the next uri via pagination in headers
def next_uri(uri)
result = fetch_uri(uri)
links = result.to_hash['link']
# stupid parsing. We'd use something real here in
# production
link_array = links.first.split(",")
link_array.collect! do |string|
string =~ /\<(.*)\>; rel="(.*)"/
[$2, $1]
end
Hash[link_array]["next"]
end
# omg hax! I don't want to deal with templates, so
# let's punt on that. You'd use a real URI templates
# parser in real code.
def parse_uri_template(uri)
uri[0..-11]
end
# Let's begin!
json = fetch_json('https://api.github.com/')
base_uri = parse_uri_template(json["gists_url"])
next_uri = next_uri(base_uri)
json = fetch_json(next_uri)
first_entry = json[0]
puts "DATA:"
puts "ID:\t#{first_entry["id"]}"
puts "URL:\t#{first_entry["url"]}"
puts "USER:\t#{first_entry["user"]["login"]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment