peterc (owner)

Revisions

gist: 60386 Download_button fork
public
Description:
Quick and messy YQL client
Public Clone URL: git://gist.github.com/60386.git
Embed All Files: show embed
yql.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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