Skip to content

Commit

Permalink
feat(values): Return error from Globals
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Oct 3, 2018
1 parent 5216cad commit fde1397
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 10 deletions.
16 changes: 8 additions & 8 deletions liquid-interpreter/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,7 @@ impl<'g> Stack<'g> {
let key = key.as_key().ok_or_else(|| {
Error::with_msg("Root index must be an object key").context("index", format!("{}", key))
})?;
let value = self
.get_val(key)
.ok_or_else(|| Error::with_msg("Invalid index").context("index", key.to_owned()))?;
let value = self.get_val(key)?;

indexes.fold(Ok(value), |value, index| {
let value = value?;
Expand All @@ -164,13 +162,15 @@ impl<'g> Stack<'g> {
})
}

fn get_val<'a>(&'a self, name: &str) -> Option<&'a Value> {
fn get_val<'a>(&'a self, name: &str) -> Result<&'a Value> {
for frame in self.stack.iter().rev() {
if let rval @ Some(_) = frame.get(name) {
return rval;
if let Some(rval) = frame.get(name) {
return Ok(rval);
}
}
self.globals.and_then(|g| g.get(name))
self.globals
.ok_or_else(|| Error::with_msg("Invalid index").context("index", name.to_owned()))
.and_then(|g| g.get(name))
}

/// Sets a value in the global context.
Expand Down Expand Up @@ -361,7 +361,7 @@ mod test {
let mut post = Object::new();
post.insert("number".into(), Value::scalar(42f64));
ctx.stack_mut().set_global_val("post", Value::Object(post));
assert!(ctx.stack().get_val("post.number").is_none());
assert!(ctx.stack().get_val("post.number").is_err());
}

#[test]
Expand Down
6 changes: 4 additions & 2 deletions liquid-interpreter/src/globals.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
use std::fmt;

use error::{Error, Result};
use value::Object;
use value::Value;

/// Immutable view into a template's global variables.
pub trait Globals: fmt::Debug {
/// Access a global variable.
fn get<'a>(&'a self, name: &str) -> Option<&'a Value>;
fn get<'a>(&'a self, name: &str) -> Result<&'a Value>;
}

impl Globals for Object {
fn get<'a>(&'a self, name: &str) -> Option<&'a Value> {
fn get<'a>(&'a self, name: &str) -> Result<&'a Value> {
self.get(name)
.ok_or_else(|| Error::with_msg("Invalid index").context("index", name.to_owned()))
}
}

0 comments on commit fde1397

Please sign in to comment.