Created
May 26, 2011 03:16
-
-
Save zerowidth/992479 to your computer and use it in GitHub Desktop.
quick api hacks
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
# requires patron, nokogiri, map | |
class Api | |
Error = Class.new(StandardError) | |
class << self | |
attr_accessor :base_url | |
end | |
attr_reader :http | |
def initialize | |
@http = Patron::Session.new | |
http.timeout = 30 | |
http.base_url = self.class.base_url or raise "no base url!" | |
end | |
def get(url, opts) | |
ttl = opts.delete :cache | |
response = http.get url | |
if response.status >= 300 | |
raise Error, "HTTP #{response.status}\n#{response.body}" | |
end | |
response.body | |
end | |
def hash_get(url, opts={}) | |
response = get url, opts | |
doc = Nokogiri::XML.parse(response) | |
return hashify(doc) | |
end | |
def html_get(url, opts={}) | |
response = get url, opts | |
return Nokogiri::HTML.parse(response) | |
end | |
def xml_get(url, opts={}) | |
response = get url, opts | |
return Nokogiri::XML.parse(response) | |
end | |
def csv_get(url, opts={}) | |
response = get url, opts | |
return csv_data(response) | |
end | |
protected | |
def hashify(xml) | |
h = Map.new | |
if xml.element_children.empty? | |
return xml.content | |
else | |
xml.element_children.each do |child| | |
if h[child.name] | |
h[child.name] = [h[child.name]] unless h[child.name].kind_of?(Array) | |
h[child.name].push hashify(child) | |
else | |
h[child.name] = hashify child | |
end | |
end | |
return h | |
end | |
end | |
def csv_data(doc) | |
data = [] | |
doc = doc.gsub(/<[^>]+>/, "") | |
FasterCSV.parse(doc, :headers => true, :return_headers => false) do |row| | |
data << row.to_hash | |
end | |
return data.reject { |h| h.empty? } | |
end | |
end | |
class YoMama < Api | |
self.base_url = "http://www.yomamajokesdb.com" | |
def random_joke | |
body = html_get "/random-joke/" | |
return body.css("#random").text.downcase | |
end | |
end | |
class FML < Api | |
self.base_url = "http://www.fmylife.com" | |
def random | |
body = html_get "/random" | |
body.css('div.post p').first.text | |
end | |
end | |
class LML < Api | |
self.base_url = "http://www.lmylife.com" | |
def random | |
body = html_get "/?sort=random" | |
body.css('div p').first.text | |
end | |
end | |
class IMMD < Api | |
self.base_url = "http://immd.icanhascheezburger.com" | |
def random | |
body = html_get "/?random" | |
body.css('blockquote').first.text | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment