Log in
updated 11:29 AM UTC, May 4, 2016

How to download Images using Ruby and how Threads help in downloading them faster

  • Written by Madhu V Rao
  • Published in Ruby

Just tried the same program which was done in Java earlier. As you can see number of Lines in Ruby program is much less compared to Java , though its little complex initially to understand the Ruby program , as you get familiar with the internals of the Ruby , Its quite easy to understand. 

Below program is quite self explanatory which uses many language constructs of Ruby like Class, Threads, Arrays , etc

 

Here it is :

require 'net/http'

class Downloader
  attr_accessor :urls, :threads

  def initiliaze()
    puts "initiated"
  end

  def download
    @threads = Array.[]()
    @urls = Array.[]("/images/comm.jpg", "/images/digital_video_broadcasting_logo.svg.png")
    @urls.each_with_index do |image, index|
      @threads << Thread.new {       # Line - 1
        Net::HTTP.start("ictforu.com") do |http|
          puts "#{index}/#{@urls.length} - #{image}"
          imageFileName = "./#{image.gsub("/", "_")}"
          resp = http.get(image)
          open(imageFileName, "wb") {|file|
            file.write(resp.body)
          }
        end
      }       # Line - 2 
    end
  end

  def wait_for_threads
    @threads.each do  |obj|
      print "."
      if  obj.alive?
        obj.join
      end
    end
  end
end

a = Time.now
download1 = Downloader.new()
download1.download
download1.wait_for_threads

b = Time.now
puts (b - a).to_s
puts "Done."

Just copy the code into an .rb file and run it

In order to see the benefits of threads, do run the same program but comment the lines (specified as # Line -1 & -2)

Creating a thread is pretty simple :

Thread.new {
  # sample code to be run as a Thread
}

 


Powered by Bullraider.com
Follow Us on Twitter
Find Us on Facebook
Follow Us on Google
Follow Us on Pinterest