Skip to content

Instantly share code, notes, and snippets.

@peterc
Created February 8, 2009 13:49
Show Gist options
  • Save peterc/60386 to your computer and use it in GitHub Desktop.
Save peterc/60386 to your computer and use it in GitHub Desktop.
Quick and messy YQL client
require 'nokogiri'
require 'open-uri'
require 'cgi'
require 'ostruct'
# YQL - Yahoo! Query Language
# http://developer.yahoo.com/yql/console/
class YQL
BASE_URL = 'http://query.yahooapis.com/v1/public/yql?format=xml&q='
def self.query(q)
begin
data = []
content = open(BASE_URL + CGI.escape(q)).read
content.gsub!(/xmlns=\".*?\"/, '') # nasty hack to rid results of namespaces
content.gsub!(/<Result/, '<result') # Yahoo's results vary in capitalization of Result - let's standardize
Nokogiri::XML(content).search('result').each do |r|
data << OpenStruct.new(Hash[*r.css("*").to_ary.collect { |a| [a.name.downcase, a.text] }.flatten])
end
data
rescue
end
end
end
if (__FILE__ == $0)
# EXAMPLE ONE - Yahoo! Local Search
restaurants = YQL.query(%{SELECT Title, Url, Rating.AverageRating FROM local.search(10) WHERE query="pizza" AND city="New York" AND state="NY" | sort(field="Rating.AverageRating") | reverse()})
restaurants.each do |r|
puts r.title
puts r.url
puts r.averagerating
end
# EXAMPLE TWO - Yahoo News!
results = YQL.query(%{select title,abstract,url,date from search.news where query="rails ruby" order by date desc})
results.each do |r|
puts r.title
puts r.url
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment