summaryrefslogtreecommitdiff
path: root/src/works/mod.rs
blob: a588ae8a7cb3c4000b692b83f99565af2aadf5c6 (plain)
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
use std::fs::File;
use std::path::PathBuf;

use anyhow::{Context, Ok, Result};
use serde::{Deserialize, Serialize};

pub mod stories;

// functionality for a group of work, e.g. stories or games
pub trait Works: for<'a> Deserialize<'a> + Serialize {
    // create works from the corresponding JSON file,
    // e.g. stories from stories.json
    fn new_from_file(workname: &str) -> Result<Self> {
        let work = serde_json::from_reader(std::io::BufReader::new(
            &File::open(PathBuf::from(workname))
                .with_context(|| format!("Failed to open {}.json", workname))?,
        ))
        .with_context(|| format!("Failed to create works from {}.json", workname))?;
        Ok(work)
    }

    // crate tera context from the group of work
    // tera context can be accessed in HTML tera templating
    fn create_tera_context(&self) -> tera::Context {
        let mut context = tera::Context::new();
        context.insert("works", &self);
        context
    }

    // render page for every work
    fn render_single_pages(self, tera_instance: &tera::Tera, template_name: &str) -> Result<Self>;

    // render corresponding overview HTML template
    // with its tera context
    fn render_overview_page(
        self,
        tera_instance: &tera::Tera,
        filename_without_extension: &str,
    ) -> Result<Self> {
        std::fs::write(
            format!("docs/{}.html", filename_without_extension).as_str(),
            tera_instance
                .render(
                    format!("{}.html", filename_without_extension).as_str(),
                    &self.create_tera_context(),
                )
                .with_context(|| {
                    format!(
                        "Failed rendering overview page for {}",
                        filename_without_extension
                    )
                })?,
        )
        .with_context(|| {
            format!(
                "Failed to write overview page for {}",
                filename_without_extension
            )
        })?;
        Ok(self)
    }
}