0

I am using twitter gem to make API calls from my app and fetch some data.

I have an array of user_ids and I want to fetch all tweets of each user by doing something like this:

user_ids.map {|user_id| Client.user_timeline(user_id)}

Is there any way to make these calls concurrent? Is there any way that I can use typhoeus or any similar gem with twitter? Is there any other way I can make this operation fast?

Uzbekjon
  • 11,655
  • 3
  • 37
  • 54
Sahil Goel
  • 103
  • 1
  • 4
  • Consider making your api calls in [separate threads](http://ruby-doc.org/core/Thread.html). – Uzbekjon Apr 23 '16 at 14:02
  • @Uzbekjon I thought of using threads at first, but I came across this [question] (http://stackoverflow.com/questions/56087/does-ruby-have-real-multithreading). As I am using CRuby, I don't think threading would help me here. Please correct me if I am wrong. – Sahil Goel Apr 23 '16 at 16:25
  • Nope, that would work just fine. The SO question you linked to discussed "true OS-level multithreading". But, you don't care how multi-threading is implemented, right. As far as it does the job. – Uzbekjon Apr 23 '16 at 16:34

1 Answers1

2

Wrap your API calls in Ruby threads to run them concurrently:

tweets, threads = [], []

threads = user_ids.map do |user_id|
  Thread.new { tweets << Client.user_timeline(user_id) }
end

threads.each(&:join)

# All the tweets are in the `tweets` array
puts tweets
Uzbekjon
  • 11,655
  • 3
  • 37
  • 54
  • Hi @Uzbekjon - this is not the correct forum, but I just want to let you know that your course on Udemy - Ruby Metaprogramming - is the best I've ever taken! This is the only way I could find to contact you and let you know! ;) – fatfrog Jun 04 '22 at 20:38
  • Hi @fatfrog. Thank you. I am glad you liked it. It means a lot. PS. I am pretty much `uzbekjon` everywhere in case you need to contact me in the future ;) – Uzbekjon Jun 12 '22 at 12:28