|
Revision 3612, 1.4 kB
(checked in by walf443, 5 years ago)
|
|
lang/ruby/path_observer: import project.
|
| Line | |
|---|
| 1 | require File.expand_path(File.join(File.dirname(__FILE__), '..', 'path_observer')) |
|---|
| 2 | |
|---|
| 3 | module PathObserver |
|---|
| 4 | class ObserveManager |
|---|
| 5 | include Observable |
|---|
| 6 | |
|---|
| 7 | def initialize glob_expr=nil, interval=1, &event_action |
|---|
| 8 | @interval = interval |
|---|
| 9 | |
|---|
| 10 | if glob_expr |
|---|
| 11 | add_paths glob_expr, &event_action |
|---|
| 12 | end |
|---|
| 13 | end |
|---|
| 14 | |
|---|
| 15 | attr_accessor :interval |
|---|
| 16 | |
|---|
| 17 | def add_path path, &event_action |
|---|
| 18 | add_observer(PathObserver::Observer.new(path, &event_action)) |
|---|
| 19 | end |
|---|
| 20 | |
|---|
| 21 | def add_paths glob_expr, &event_action |
|---|
| 22 | Path.glob(glob_expr).each do |path| |
|---|
| 23 | add_path path, &event_action |
|---|
| 24 | end |
|---|
| 25 | end |
|---|
| 26 | |
|---|
| 27 | def observe method |
|---|
| 28 | last_result_of = {} |
|---|
| 29 | @observer_peers.each do |observer| |
|---|
| 30 | last_result_of[observer.path.to_s] = observer.path __send__(method) |
|---|
| 31 | end |
|---|
| 32 | |
|---|
| 33 | loop do |
|---|
| 34 | begin |
|---|
| 35 | sleep @interval |
|---|
| 36 | |
|---|
| 37 | current_result_of = {} |
|---|
| 38 | @observer_peers.each do |observer| |
|---|
| 39 | current_result_of[observer.path.to_s] = observer.path.__send__(method) |
|---|
| 40 | end |
|---|
| 41 | |
|---|
| 42 | temp_touple = current_result_of.select {|key, val| val != last_result_of[key] } |
|---|
| 43 | if temp_touple.size > 0 |
|---|
| 44 | temp_touple.each do |hash| |
|---|
| 45 | changed |
|---|
| 46 | notify_observers hash.first, hash.last |
|---|
| 47 | end |
|---|
| 48 | last_result_of = current_result_of |
|---|
| 49 | end |
|---|
| 50 | rescue Interrupt |
|---|
| 51 | return |
|---|
| 52 | rescue Exception |
|---|
| 53 | next |
|---|
| 54 | end |
|---|
| 55 | end |
|---|
| 56 | end |
|---|
| 57 | end |
|---|
| 58 | end |
|---|