5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ファイルの変更、追加、削除を監視するgem

Posted at

Rubyで特定のディレクトリ配下のファイルの変更を監視したいときに使えるgemが"listen"。
https://github.com/guard/listen

ファイルを監視して特定のタスクを走らせるguardというgemが有名だが、その内部で使われている。
MacOS,Linux,BSD系,Windowsに対応している。

使い方

listenのインストール。普通のgemと同様。Gemfileに gem 'listen', '~> 3.0'と書いてbundleを実行。

サンプルコード

listen_sample.rb
require 'listen'

listener = Listen.to('dir1', 'dir2') do |modified, added, removed|
  puts "modified absolute path: #{modified}"
  puts "added absolute path: #{added}"
  puts "removed absolute path: #{removed}"
end
listener.start # not blocking
sleep

これを実行して、別のターミナルでdir1やdir2の配下にファイルを作ってみる。

touch dir1/hoge

すると、listenを実行している方のターミナルに

modified absolute path: []
added absolute path: ["/Users/murase/sandbox/listen_rb/dir1/hoge"]
removed absolute path: []

と表示される。
またファイルに書き込みをすると(echo "foobar" >> dir1/hogeを実行)、

modified absolute path: ["/Users/murase/sandbox/listen_rb/dir1/hoge"]
added absolute path: []
removed absolute path: []

と表示される。

多くの場合はGuardを使えばことは足りると思うが、より柔軟に制御したい場合は"listen"を単体で使うと良いかもしれない。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?