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
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
//! Edo is a VERY simple templating language. It allows you to register handlers that are executed when their matching names are found in the template.
//!
//! For example, with the template `"Hello {name}"`, the `name` handler would be executed and the string it returns would be substituted in place of the original `{name}`. Handler functions can also accept arguments, which are passed in as a `Vec<str>`.
//!
//! # Examples
//!
//! ### Static input
//! ```
//! use edo::Edo;
//!
//! let mut template = Edo::new("Hello {name}").unwrap();
//! template.register_static("name", "World!");
//! let output = template.render();
//! assert_eq!(output, "Hello World!");
//! ```
//!
//! ### Simple Handler
//! ```
//! use edo::Edo;
//!
//! let mut template = Edo::new("Hello {name}").unwrap();
//! template.register_handler("name", |_| Ok("World!".to_string()));
//! let output = template.render();
//! assert_eq!(output, "Hello World!");
//! ```
//!
//! ### Handler With Arguments 
//! ```
//! use edo::Edo;
//!
//! let mut template = Edo::new("{say_hello(World)}").unwrap();
//! template.register_handler("say_hello", |args| Ok(format!("Hello {}", args[0])));
//! let output = template.render();
//! assert_eq!(output, "Hello World");
//! ```
#![deny(missing_docs)]

#[macro_use]
extern crate nom;

pub mod error;
mod parse;

use std::str;
use std::collections::HashMap;

use error::EdoError;
use parse::Expression;

enum ValueProducer<'a> {
    Handler(Box<Fn(Vec<&'a str>) -> Result<String, String>>),
    Static(String),
}

/// A single template. Allows registering of handlers and rendering
pub struct Edo<'a> {
    #[doc(hidden)]
    value_producers: HashMap<&'a str, ValueProducer<'a>>,
    template: Vec<Expression<'a>>,
}

impl<'a> Edo<'a> {
    /// Creates a new template instance.
    ///
    /// # Examples
    /// ```no_run
    /// # #![allow(unused_variables)]
    /// # use edo::Edo;
    /// let template = Edo::new("Hello {name}");
    /// ```
    pub fn new(template_string: &'a str) -> Result<Edo<'a>, EdoError> {
        Ok(Edo {
            value_producers: HashMap::new(),
            template: try!(parse::parse(template_string)),
        })
    }

    /// Register a new function handler
    ///
    /// # Examples
    /// ```no_run
    /// # #![allow(unused_variables)]
    /// # use edo::Edo;
    /// let mut template = Edo::new("Hello {name}").unwrap();
    /// template.register_handler("name", |_| Ok("World!".to_string()));
    /// ```
    pub fn register_handler<F>(&mut self, name: &'a str, handler: F) where
        F: 'static + Fn(Vec<&'a str>) -> Result<String, String> {
        self.value_producers.insert(name, ValueProducer::Handler(Box::new(handler)));
    }

    /// Register a static replacement
    ///
    /// # Examples
    /// ```no_run
    /// # #![allow(unused_variables)]
    /// # use edo::Edo;
    /// let mut template = Edo::new("Hello {name}").unwrap();
    /// template.register_static("name", "World!");
    /// ```
    pub fn register_static<S: Into<String>>(&mut self, name: &'a str, input: S) {
        self.value_producers.insert(name, ValueProducer::Static(input.into()));
    }

    /// Render template into a string
    ///
    /// # Examples
    /// ```
    /// # use edo::Edo;
    /// let mut template = Edo::new("Hello {name}").unwrap();
    /// template.register_handler("name", |_| Ok("World!".to_string()));
    /// let output = template.render();
    /// assert_eq!(output, "Hello World!");
    /// ```
    // TODO: add a strict mode that errors when there is no handler
    pub fn render(&mut self) -> String {
        self.render_with_errors().0
    }

    /// Render a template into a string and recieve a vector of errors
    ///
    /// # Examples
    /// ```
    /// # use edo::Edo;
    /// let mut template = Edo::new("Hello {name}").unwrap();
    /// template.register_handler("name", |_| Err("Something Broke".to_string()));
    /// let (output, errors) = template.render_with_errors();
    /// assert_eq!(output, "Hello ");
    /// assert_eq!(errors, vec!["Something Broke".to_string()]);
    /// ```
    pub fn render_with_errors(&mut self) -> (String, Vec<String>) {
        // Keep track of errors
        let mut errors: Vec<String> = vec![];

        // Iterate over the template and
        // 1. Leave literals untouched
        // 2. Call the handlers for each function call and replace within the output
        (self.template.iter()
            .map(|expression| match *expression {
                Expression::Literal(text) => text.to_string(),
                Expression::Function { name, ref arguments } => {
                    match self.value_producers.get(name) {
                        None => "".to_string(),
                        Some(value_producer) => match value_producer {
                            &ValueProducer::Handler(ref handler) => match handler(arguments.clone()) {
                                Ok(string) => string,
                                Err(error_string) => {
                                    errors.push(error_string);
                                    "".to_string()
                                },
                            },
                            &ValueProducer::Static(ref value) => value.clone(),
                        },
                    }
                }
            })
            .collect::<Vec<String>>()
            .concat(), errors)
    }
}

#[cfg(test)]
mod tests {
    use super::Edo;

    #[test]
    fn create_new_edo() {
        let edo = Edo::new("Hello {name}");
        assert!(edo.is_ok());
    }

    #[test]
    fn register_handler() {
        let mut edo = match Edo::new("Hello {name}") {
            Ok(edo) => edo,
            Err(err) => panic!(err),
        };
        edo.register_handler("name", |_| Ok("World!".to_string()));
        assert!(edo.value_producers.get("name").is_some());
    }

    #[test]
    fn register_static() {
        let mut edo = match Edo::new("Hello {name}") {
            Ok(edo) => edo,
            Err(err) => panic!(err),
        };
        edo.register_static("name", "World!");
        assert!(edo.value_producers.get("name").is_some());
    }

    #[test]
    fn render_template() {
        let mut edo = match Edo::new("Hello {name}") {
            Ok(edo) => edo,
            Err(err) => panic!(err),
        };
        edo.register_handler("name", |_| Ok("World!".to_string()));
        assert_eq!(
            edo.render(),
            "Hello World!"
        );
    }

    #[test]
    fn render_template_with_missing_handler() {
        let mut edo = match Edo::new("Hello {name}") {
            Ok(edo) => edo,
            Err(err) => panic!(err),
        };
        assert_eq!(
            edo.render(),
            "Hello "
        );
    }

    #[test]
    fn render_template_with_arguments() {
        let mut edo = match Edo::new("Hello {name(Gio, yes)}") {
            Ok(edo) => edo,
            Err(err) => panic!(err),
        };
        edo.register_handler("name", |args|
            Ok(format!("{}{}", args[0], if args[1] == "yes" { "!" } else { "" }))
        );
        assert_eq!(
            edo.render(),
            "Hello Gio!"
        );
    }

    #[test]
    fn render_with_errors() {
        let mut edo = match Edo::new("Hello {name}") {
            Ok(edo) => edo,
            Err(err) => panic!(err),
        };
        edo.register_handler("name", |_| Err("BORK".to_string()));
        let (output, errors) = edo.render_with_errors();
        assert_eq!(output, "Hello ");
        assert_eq!(errors, vec!["BORK"]);
    }
}