ディレクトリを監視してファイルをコピーするスクリプト

某用途で使用したスクリプトです。

require "fileutils"
include FileUtils

COPY_FROM = 'C:\user\data'
COPY_TO = File.expand_path(".")
TARGET_SIZE = 1e6
SLEEP_SECOND = 10

def putlog(msg)
  puts "#{Time.now}: #{msg}"
end

cd COPY_FROM
before_time = nil
loop do
  files = Dir.glob("*")
  target_files = files.select {|f| File.size(f) > TARGET_SIZE }
  latest_file = target_files.max_by {|f| File.mtime(f) }
  if latest_file
    modify_time = File.mtime(latest_file)
    if before_time != modify_time
      ftime = modify_time.strftime("%Y%m%d%H%M%S")
      fname = "#{ftime}_#{latest_file}"
      cp_r(latest_file, File.join(COPY_TO, fname))
      putlog "Copy file to #{fname}."
      before_time = modify_time
    else
      putlog "Not found of new file."
    end
  else
    putlog "Not found of target file."
  end
  sleep SLEEP_SECOND
end

簡単に説明すると、コピー元のディレクトリ(COPY_FROM)内の条件に合ったファイル群(target_files)のうち最新のもの(latest_file)が更新されていた場合(before_time != modify_time)、コピー先のディレクトリ(COPY_TO)にコピー(cp_r)します。何に使ったかはナイショ。