Fetch Gists from the API
require 'net/http' | |
require 'json' | |
# a simple wrapper to do an HTTP GET | |
def fetch_uri(uri) | |
Net::HTTP.get_response(URI(uri)) | |
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"]}" |
This comment has been minimized.
This comment has been minimized.
oh? This worked for me, unmodified. weird. |
This comment has been minimized.
This comment has been minimized.
I'm getting |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
had to modify for https to work