Check that an image is available to be served I have a couple of images in my database and I need to check if the images are still good or if they're deleted or corrupted. I came up with a solution but it's very slow. I was wondering if there was a way to make this faster.

img = 'http://some_image_cdn.com/images/image.jpg'
begin
  Nokogiri::HTML(open(img))
rescue
  # do something 
end
To make this more efficient, you need to break down this problem into smaller pieces. From your description you are:


Testing the image to see if it exists
Testing the image to see if it is corrupted


The first test is pretty easy, and can be optimized by issuing a HEAD request to the server. The second test is where things get inefficient because you need to download the image and parse it.

Something like a remote image verifier that has methods to test for the image existence and corruption would be beneficial:

class RemoteImageVerifier
  def image_exists?(uri)
    Net::HTTP.start(uri.host, uri.port) do |http|
      begin
        response = http.request_head uri.path
        # check response["header-name"] if need be
        true
      rescue Net::HTTPNotFound
        # Image URL is no longer valid
        false
      rescue Exception
        # Another unknown error happened
        false
      end
    end
  end

  def image_corrupted?(uri)
    Net::HTTP.start(uri.host, uri.port) do |http|
      begin
        response = http.request_get uri.path
        # parse response.body as a JPEG
        false
      rescue Exception
        # Another unknown error happened
        true
      end
    end
  end
end


And to use it:

verifier = RemoteImageVerifier.new

verifier.image_exists? 'http://some_image_cdn.com/images/image.jpg'
verifier.image_corrupted? 'http://some_image_cdn.com/images/image.jpg'