Poyda
Poyda

Reputation: 108

Ruby copy file to another location when download complete

I have started downloading a large file (NOT through ruby), and then realised I was downloading to the wrong location. I won't be at my computer when the download is complete, so is there a way of having ruby register that the file is downloaded, and copy that file to another folder overnight?

I understand how to copy the file, but is it possible for Ruby to run a test every so often, or start a process on computer process completion?

Upvotes: 1

Views: 331

Answers (1)

Aetherus
Aetherus

Reputation: 8898

Maybe the gem listen can help you. You just need to listen to the directory where your downloaded file resides, optionally specify the filename you want to monitor, track the timestamp of each modification, and if the last modification is, say, 10 minutes ago, copy the file to the new directory.

require 'listen'
require 'fileutils'
require 'time'

modified_at = Time.now

listener = Listen.to('/path/to/download/dir', only: /^downloaded-file$/) do |modified|
  modified && (modified_at = Time.now)
end

listener.start

loop do
  if Time.now - modified_at > 600
    listener.stop
    FileUtils.cp('/path/to/download/dir/downloaded-file', '/path/to/new/dir')
    break
  end
  sleep 60
end

Upvotes: 2

Related Questions