diff --git a/Gemfile b/Gemfile index 59fc384..6eb073f 100644 --- a/Gemfile +++ b/Gemfile @@ -2,6 +2,7 @@ source 'https://rubygems.org' ruby "3.2.2" +gem 'concurrent-ruby' gem 'pry' group :test do diff --git a/Gemfile.lock b/Gemfile.lock index cc30155..5114af3 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -4,6 +4,7 @@ GEM addressable (2.8.4) public_suffix (>= 2.0.2, < 6.0) coderay (1.1.3) + concurrent-ruby (1.2.2) crack (0.4.5) rexml diff-lcs (1.5.0) @@ -36,6 +37,7 @@ PLATFORMS arm64-darwin-20 DEPENDENCIES + concurrent-ruby pry rspec webmock diff --git a/README.md b/README.md index c8a3641..6eb67ed 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ Image Downloader is a command-line tool that downloads images from a list of URL ## Dependencies +- concurrent-ruby - pry - rspec - webmock diff --git a/lib/image_downloader.rb b/lib/image_downloader.rb index 0212171..d3bca37 100644 --- a/lib/image_downloader.rb +++ b/lib/image_downloader.rb @@ -1,12 +1,15 @@ require 'open-uri' require 'net/http' +require 'concurrent' class ImageDownloader def self.download_images(urls, target_dir = "./images") Dir.mkdir(target_dir) unless File.exist?(target_dir) - threads = urls.map do |url| - Thread.new do + pool = Concurrent::FixedThreadPool.new(10) + + urls.each do |url| + pool.post do begin uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) @@ -28,6 +31,7 @@ def self.download_images(urls, target_dir = "./images") end end - threads.each(&:join) # Wait for all threads to finish + pool.shutdown + pool.wait_for_termination end end