@@ -13,38 +13,40 @@ class Watcher
13
13
MODIFIED = 1
14
14
DELETED = 2
15
15
16
- attr_accessor :sleep_time , :priority
17
- attr_reader :directory
18
-
19
- def initialize ( &client_callback )
16
+ attr_reader :directory , :pattern , :priority
17
+
18
+ # Create a file system watcher. Start it by calling #start.
19
+ #
20
+ # @param options[:directory] the directory to watch (default ".")
21
+ # @param options[:pattern] the glob pattern to search under the watched directory (default "**/*")
22
+ # @param options[:priority] the priority of the watcher thread (default 0)
23
+ #
24
+ def initialize ( options = { } , &client_callback )
20
25
@client_callback = client_callback
21
26
22
- @sleep_time = 1
23
- @priority = 0
27
+ options = {
28
+ :directory => "." ,
29
+ :pattern => "**/*" ,
30
+ :priority => 0 ,
31
+ } . merge ( options )
24
32
25
- @directory = nil
26
- @files = [ ]
33
+ @pattern = options [ :pattern ]
34
+ @directory = options [ :directory ]
35
+ if FileTest . exists? ( directory ) && FileTest . readable? ( directory ) then
36
+ @directory = Directory . new ( directory , @pattern )
37
+ else
38
+ raise InvalidDirectoryError , "Dir '#{ directory } ' either doesnt exist or isnt readable"
39
+ end
40
+ @priority = options [ :priority ]
27
41
28
42
@found = nil
29
43
@first_time = true
30
44
@thread = nil
31
-
32
- end
33
-
34
- # add a directory to be watched
35
- # @param dir the directory to watch
36
- # @param expression the glob pattern to search under the watched directory
37
- def add_directory ( dir , expression = "**/*" )
38
- if FileTest . exists? ( dir ) && FileTest . readable? ( dir ) then
39
- @directory = Directory . new ( dir , expression )
40
- else
41
- raise InvalidDirectoryError , "Dir '#{ dir } ' either doesnt exist or isnt readable"
42
- end
43
45
end
44
46
45
47
def prime
46
48
@first_time = true
47
- @found = Hash . new ( )
49
+ @found = { }
48
50
examine
49
51
@first_time = false
50
52
end
@@ -58,13 +60,15 @@ def start
58
60
59
61
@thread = Thread . new do
60
62
# todo: multiple dirs
63
+
61
64
# todo: convert each dir's pattern to a regex and get Listen to do the file scan for us
62
- @listener = Listen ::Listener . new ( @directory . dir ) do |modified , added , removed |
65
+ regexp = Glob . new ( @pattern ) . to_regexp
66
+ puts "regexp is #{ regexp . inspect } "
67
+ @listener = Listen ::Listener . new ( @directory . dir , :filter => regexp ) do |modified , added , removed |
63
68
#d { modified }
64
69
#d { added }
65
70
#d { removed }
66
71
examine
67
- sleep ( @sleep_time )
68
72
end
69
73
@listener . start
70
74
end
0 commit comments