Search code examples
rubytwittertwitter-gem

Twitter ruby gem .search request multiple responses


In the following code I specify that I want to make 1 request to the twitter api, but when I puts the output to terminal I continue to receive many responses until I kill the program. How can I limit it to only the specified amount of requests? I am new to ruby so I may be missing something obviously here.

Docs to the twitter gem api

require 'twitter'

...

client = Twitter::REST::Client.new do |config|

  config.consumer_key        = credentials[:consumer_key]
  config.consumer_secret     = credentials[:consumer_secret]
  config.access_token        = credentials[:access_token]
  config.access_token_secret = credentials[:access_token_secret]

end

search_results = client.search "China", {:count => 1, :lang => 'en', :result_type => 'recent'}

search_results.each do |value|

    puts value.user.screen_name

end

Solution

  • As docs state,

    :count (Integer) — The number of tweets to return per page, up to a maximum of 100.

    So, that is kinda reverse for what you're trying to achieve: the more count is, the less http requests you gonna make (as each of them would contain more tweets). Note that you can not set count to an amount more than 100, so the only way to restrict amount of requests in case there is a huge amount of tweets would be

    search_results.take(requests_amount)
    # => made requests_amount requests, returns requests_amount pages
    # each of page should contain up to count tweets, with max of 100