libstubble 0.3.5

Stubble APIs
Documentation
//! The `template` module contains resources related to rendering Stubs from Handlebars templates.
use crate::stub::Stub;
use anyhow::{bail, Result};
use handlebars_misc_helpers;

/// The Markdown stub template as a str.
pub const MARKDOWN_TEMPLATE: &str = include_str!(std::concat!(
    std::env!("CARGO_MANIFEST_DIR"),
    "/src/templates/markdown.hbs"
));
/// The Org Mode stub template as a str.
pub const ORG_TEMPLATE: &str = include_str!(std::concat!(
    std::env!("CARGO_MANIFEST_DIR"),
    "/src/templates/org.hbs"
));
/// The Pico-8 stub template as a str.
pub const PICO8_TEMPLATE: &str = include_str!(std::concat!(
    std::env!("CARGO_MANIFEST_DIR"),
    "/src/templates/pico8.hbs"
));


/// A trait providing methods for rendering a `Stub` into a `String` and returning it as a `Result`.
pub trait Render {
    /// Given a `String` containing a Handlebars template, render the template
    /// using the stub's properties and return a `String` `Result`.
    fn render(&mut self, template: String) -> Result<String>;

    /// Given a `String` referencing a built-in format, render the `Stub`
    /// using that format's template and return a `String` `Result`.
    fn render_to(&mut self, format: String) -> Result<String>;
}

impl Render for Stub {
    fn render(&mut self, template: String) -> Result<String> {
        let mut hbs = handlebars_misc_helpers::new_hbs();
        handlebars_misc_helpers::register(&mut hbs);

        hbs.register_template_string("stub", template)?;

        let context = serde_json::value::to_value(self)?;

        match hbs.render("stub", &context) {
            Ok(c) => Ok(c.to_string()),
            Err(err) => bail!("Could not render stub! {:?}", err),
        }
    }

    fn render_to(&mut self, format: String) -> Result<String> {
        match format.as_str() {
            "md" => self.render(String::from(MARKDOWN_TEMPLATE)),
            "org" => self.render(String::from(ORG_TEMPLATE)),
            "pico8" => self.render(String::from(PICO8_TEMPLATE)),
            &_ => bail!("Unknown output type '{}'", format),
        }
    }
}