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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

use std::path::{Path, PathBuf};
use std::collections::HashMap;
use glob::glob;
use Template;


/// Compiled template cache
///
/// # Examples
///
/// ```
/// use mage::Cache;
///
/// let mut cache = Cache::new();
/// cache.load("examples", "html");
///
/// let template = cache.get("main").unwrap();
/// let output = template.render().unwrap();
/// ```
///
#[derive(Default)]
pub struct Cache {
    raw: HashMap<String, Template>,
}

impl Cache {
    /// Create a cache.
    pub fn new() -> Cache {
        Cache { ..Default::default() }
    }

    /// Load templates with the given root and extension.
    pub fn load<P, T>(&mut self, root: P, extension: T)
        where P: AsRef<Path>,
              T: AsRef<str>
    {
        for entry in glob(&format!("{}/**/*.{}", root.as_ref().display(), extension.as_ref()))
            .unwrap() {
            let pathbuf = entry.unwrap();
            let path = pathbuf.strip_prefix(root.as_ref()).unwrap();
            let view = get_view(path);
            self.raw.insert(fix_view_name(&view),
                            Template::new()
                                .root(root.as_ref())
                                .extension(extension.as_ref())
                                .open(&view)
                                .unwrap()
                                .compile()
                                .unwrap());
        }
    }

    /// Find cached template.
    pub fn get(&self, view: &str) -> Option<&Template> {
        self.raw.get(view)
    }
}

fn get_view(view: &Path) -> PathBuf {
    let filename = view.file_stem().unwrap().to_str().unwrap();
    let mut view_path = view.parent().unwrap().to_path_buf();
    view_path.push(filename);
    view_path
}

fn fix_view_name(view: &Path) -> String {
    view.display().to_string().replace('\\', "/")
}