Skip to content

Instantly share code, notes, and snippets.

@rosylilly
Created June 18, 2011 22:35
Show Gist options
  • Save rosylilly/1033569 to your computer and use it in GitHub Desktop.
Save rosylilly/1033569 to your computer and use it in GitHub Desktop.
ファイルの更新を検知するFile.watchメソッドを生やす
require 'thread'
class File
# ファイルの更新を検知して、渡されたブロックを実行する
# 更新検知部分のコードは[ここ](http://ja.doukaku.org/comment/387/)のを丸パクリ
def self.watch(fileName, &function)
raise AugumentsError if(!File.exist?(fileName) || !function)
thread = Thread.new(fileName, function){ | _fileName, _function |
Thread.pass
last_mtime = File.mtime(_fileName)
loop do
unless((mtime = File.mtime(_fileName)) == last_mtime)
_function.call(_fileName, mtime)
last_mtime = mtime
end
sleep(0.1)
Thread.pass
end
}
thread.join
end
end
if($0 == __FILE__)
File.watch("test") do | fn, mt |
puts "#{fn} is Updated!"
p mt
end
loop do
sleep(1)
Thread.pass
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment