Skip to content

Commit

Permalink
Round filter with method parameter.
Browse files Browse the repository at this point in the history
  • Loading branch information
Luis Moreno committed Aug 19, 2020
1 parent d12bd48 commit 80b496a
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/filters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub enum Filter {
Lower,
Max,
Min,
Round,
String,
Sum,
Title,
Expand All @@ -41,6 +42,7 @@ impl Filter {
"lower" => Ok(Filter::Lower),
"max" => Ok(Filter::Max),
"min" => Ok(Filter::Min),
"round" => Ok(Filter::Round),
"string" => Ok(Filter::String),
"sum" => Ok(Filter::Sum),
"title" => Ok(Filter::Title),
Expand Down Expand Up @@ -107,6 +109,14 @@ impl Filter {
Filter::Lower => base_value.lower(),
Filter::Max => base_value.max(), // TODO Accept params
Filter::Min => base_value.min(), // TODO Accept params
Filter::Round => {
let parameters = if params.is_some() {
params.as_ref().unwrap().parse(vec!["method"], context)?
} else {
HashMap::default()
};
base_value.round(parameters)
}
Filter::String => Ok(Value::String(base_value.to_string())),
Filter::Sum => base_value.sum(), // TODO: ACcept params
Filter::Title => base_value.title(),
Expand Down
22 changes: 22 additions & 0 deletions src/value/filters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,28 @@ impl Value {
_ => Err(Error::from(ErrorKind::InvalidOperation)),
}
}
pub fn round(self, mut params: HashMap<&str, Value>) -> Result<Self> {
let method = params
.remove("method")
.unwrap_or_else(|| Value::String("common".to_string()));

if let Value::Double(value) = self {
if let Value::String(method_str) = method {
match method_str.as_str() {
"common" => Ok(Value::Double(value.round())),
"ceil" => Ok(Value::Double(value.ceil())),
"floor" => Ok(Value::Double(value.floor())),
_ => Err(Error::from(ErrorKind::InvalidValueType)),
}
} else {
Err(Error::from(ErrorKind::InvalidValueType))
}
} else if let Value::Integer(value) = self {
Ok(Value::Integer(value))
} else {
Err(Error::from(ErrorKind::InvalidValueType))
}
}
pub fn sum(self) -> Result<Self> {
if let Value::ValuesList(values_list) = self {
let value: f64 = values_list
Expand Down
7 changes: 7 additions & 0 deletions tests/filters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,10 @@ fn title_filter() -> Result<()> {
assert_render_template_eq("{{ 'hello world!' | title }}", "Hello World!", None)?;
assert_render_template_eq("{{ 'HellO wOrlD!' | title }}", "Hello World!", None)
}

#[test]
fn round_filter() -> Result<()> {
assert_render_template_eq("{{ 5.8 | round }}", "6.0", None)?;
assert_render_template_eq("{{ 3.14 | round(method='ceil') }}", "4.0", None)?;
assert_render_template_eq("{{ 5.8 | round(method='floor') }}", "5.0", None)
}

0 comments on commit 80b496a

Please sign in to comment.