Switching to a combined ContextElement trait for Walkable and Renderable

This commit is contained in:
Tom Alexander 2020-04-11 22:19:54 -04:00
parent 07e5c9f0af
commit 5efa650b67
Signed by: talexander
GPG Key ID: D3A179C9A53C0EDE
3 changed files with 39 additions and 12 deletions

View File

@ -9,4 +9,5 @@ pub use renderable::Renderable;
pub use renderer::compile_template;
pub use renderer::CompiledTemplate;
pub use renderer::DustRenderer;
pub use walkable::ContextElement;
pub use walkable::Walkable;

View File

@ -111,9 +111,32 @@ impl<'a> DustRenderer<'a> {
#[cfg(test)]
mod tests {
use super::*;
use crate::renderer::walkable::ContextElement;
impl<I: Walkable> Walkable for HashMap<&str, I> {
fn walk(&self, segment: &str) -> &dyn Walkable {
impl ContextElement for u32 {}
impl ContextElement for &str {}
impl<I: ContextElement> ContextElement for HashMap<&str, I> {}
impl Renderable for u32 {
fn render(&self) -> std::string::String {
self.to_string()
}
}
impl Renderable for &str {
fn render(&self) -> std::string::String {
self.to_string()
}
}
impl<I: ContextElement> Renderable for HashMap<&str, I> {
fn render(&self) -> std::string::String {
panic!("Attempted to render a hashmap");
}
}
impl<I: ContextElement> Walkable for HashMap<&str, I> {
fn walk(&self, segment: &str) -> &dyn ContextElement {
self.get(segment).unwrap()
}
@ -123,7 +146,7 @@ mod tests {
}
impl Walkable for &str {
fn walk(&self, segment: &str) -> &dyn Walkable {
fn walk(&self, segment: &str) -> &dyn ContextElement {
panic!("Tried to walk down a str");
}
@ -133,7 +156,7 @@ mod tests {
}
impl Walkable for u32 {
fn walk(&self, segment: &str) -> &dyn Walkable {
fn walk(&self, segment: &str) -> &dyn ContextElement {
panic!("Tried to walk down a str");
}
@ -142,7 +165,10 @@ mod tests {
}
}
fn do_the_walk<'a>(context: &'a dyn Walkable, path: &Vec<&str>) -> &'a dyn Walkable {
fn do_the_walk<'a>(
context: &'a dyn ContextElement,
path: &Vec<&str>,
) -> &'a dyn ContextElement {
let mut output = context;
for elem in path.iter() {
@ -171,11 +197,11 @@ mod tests {
.iter()
.cloned()
.collect();
assert_eq!(do_the_walk(&context, &vec!["cat"]).val(), "kitty");
// assert_eq!(do_the_walk(&number_context, &vec!["tiger"]), &3);
assert_eq!(do_the_walk(&context, &vec!["cat"]).render(), "kitty");
assert_eq!(do_the_walk(&number_context, &vec!["tiger"]).render(), "3");
// assert_eq!(
// do_the_walk(&deep_context, &vec!["tiger"]),
// &[("food", "people")].iter().cloned().collect()
// do_the_walk(&deep_context, &vec!["tiger", "food"]).render(),
// "people"
// );
}
}

View File

@ -1,9 +1,9 @@
use super::renderable::Renderable;
pub trait Walkable {
// type Output: Walkable;
pub trait ContextElement: Walkable + Renderable {}
fn walk(&self, segment: &str) -> &dyn Walkable;
pub trait Walkable {
fn walk(&self, segment: &str) -> &dyn ContextElement;
fn val(&self) -> String;
}