Class: TwitterSearch::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/twitter_search.rb

Constant Summary collapse

TWITTER_SEARCH_API_URL =
'http://search.twitter.com/search.json'
'http://search.twitter.com/trends/current.json'
DEFAULT_TIMEOUT =
5

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(agent = 'twitter-search', timeout = DEFAULT_TIMEOUT) ⇒ Client

Returns a new instance of Client.



23
24
25
26
# File 'lib/twitter_search.rb', line 23

def initialize(agent = 'twitter-search', timeout = DEFAULT_TIMEOUT)
  @agent = agent
  @timeout = timeout
end

Instance Attribute Details

#agentObject

Returns the value of attribute agent.



20
21
22
# File 'lib/twitter_search.rb', line 20

def agent
  @agent
end

#timeoutObject

Returns the value of attribute timeout.



21
22
23
# File 'lib/twitter_search.rb', line 21

def timeout
  @timeout
end

Instance Method Details

#headersObject



28
29
30
31
# File 'lib/twitter_search.rb', line 28

def headers
  { "Content-Type" => 'application/json',
    "User-Agent"   => @agent }
end

#query(opts = {}) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/twitter_search.rb', line 33

def query(opts = {})
  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 = timeout

  res = http.start { |http|
    http.get("#{url.path}?#{url.query}", headers)
  }
  
  if res.code == '404'
    raise TwitterSearch::SearchServerError, "Twitter responded with a 404 for your query. It is likely too complicated to process."
  end
  
  json = res.body
  
  Tweets.new JSON.parse(json)
end


56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/twitter_search.rb', line 56

def trends(opts = {})
  url = URI.parse(TWITTER_TRENDS_API_URL)
  if opts['exclude_hashtags']
    url.query = sanitize_query_hash({ :exclude_hashtags => opts['exclude_hashtags'] })
  end

  req  = Net::HTTP::Get.new(url.path)
  http = Net::HTTP.new(url.host, url.port)
  http.read_timeout = timeout

  json = http.start { |http|
    http.get("#{url.path}?#{url.query}", headers)
  }.body
  
  Trends.new JSON.parse(json)
end