1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
use middleware::HandlebarsEngine;

use notify::{RecommendedWatcher, Error, Watcher};
use std::path::Path;
use std::sync::mpsc::channel;
use std::sync::Arc;
use std::thread;

fn _watch (p: String) -> Result<(), Error>{
    let (tx, rx) = channel();
    let mut watcher: RecommendedWatcher = try!(Watcher::new(tx));
    try!(watcher.watch(&Path::new(&p)));
    let _ = rx.recv();
    Ok(())
}

pub trait Watchable {
    fn watch(&self);
}

impl Watchable for Arc<HandlebarsEngine> {
    #[allow(while_true)]
    fn watch (&self) {
        let hbs = self.clone();
        thread::spawn(move || {
            println!("watching path: {}", hbs.prefix);
            while true {
                if let Ok(_) = _watch(hbs.prefix.clone()) {
                    println!("things changed");
                    hbs.reload();
                } else {
                    panic!("Failed to watch template directory.");
                }
            }
        });

    }
}