rails twitter search using search.atom
Posted: July 23rd, 2009 | Author: FreedomCoder | Filed under: Open Source, Programming | Tags: how-to, Open Source, Programming, twitter | No Comments »
Recently, I had to create a twitter live feed for a work I’m doing…. so I found the gems for searching in twitter, but all of them were working with the search.json api, but since my client wanted the same results that he saw in twitter.search.com, I created a lib for that project (following the gem example code), in order to use the search.atom api and parse the xml results with hpricot.
If you deal with the same problem, here you have the code
require ‘rubygems’
require ‘net/http’
require ‘cgi’
class Twitter
TWITTER_SEARCH_API_URL = ‘http://search.twitter.com/search.atom’
DEFAULT_TIMEOUT = 5
HEADERS = { “Content-Type” => ‘application/rss+xml’,
“User-Agent” => ‘twitter-search’ }
def self.search(opts)
search_for = ‘#twitter’
url = URI.parse(TWITTER_SEARCH_API_URL)
url.query = sanitize_query(opts)
ensure_no_location_operators(url.query)
req = Net::HTTP::Get.new(url.path)
http = Net::HTTP.new(url.host, url.port)
http.read_timeout = DEFAULT_TIMEOUT
res = http.start { |h| h.get(”#{url.path}?#{url.query}”, HEADERS) }
if res.code == ‘404′
raise “Twitter responded with a 404 for your query”
end
self.parse_search(res.body)
end
def self.sanitize_query(opts)
if opts.is_a? String
“q=#{CGI.escape(opts)}”
elsif opts.is_a? Hash
“#{sanitize_query_hash(opts)}”
else
raise “sanitique_query expects a String or a Hash”
end
end
def self.sanitize_query_hash(query_hash)
query_hash.collect{|key, value| “#{CGI.escape(key.to_s)}=#{CGI.escape(value.to_s)}” }.join(’&’)
end
def self.ensure_no_location_operators(query_string)
if query_string.include?(”near%3A”) ||
query_string.include?(”within%3A”)
raise “near: and within: are available from the Twitter Search web interface, but not the API. The API requires the geocode parameter. See dancroak/twitter-search README.”
end
end
def self.parse_search(body)
doc = Hpricot.parse(body)
entries = []
items = (doc/:entry)
items.each do |raw_item|
entry = {}
entry
(Via Rorra’s blog.) Original Link: rails twitter search using search.atom