Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add date filter #42

Merged
merged 4 commits into from
Jun 30, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ build = "build.rs"
[dependencies]
regex = "0.1"
lazy_static = "0.1.15"
chrono = "0.2.22"
clippy = {version = "0.0", optional = true}

[build-dependencies]
Expand Down
51 changes: 50 additions & 1 deletion src/filters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ use std::error::Error;
use value::Value;
use value::Value::*;

use chrono::DateTime;

use self::FilterError::*;

#[derive(Debug)]
#[derive(Debug, PartialEq, Eq)]
pub enum FilterError {
InvalidType(String),
InvalidArgumentCount(String),
Expand Down Expand Up @@ -297,6 +299,25 @@ pub fn join(input: &Value, args: &[Value]) -> FilterResult {
}
}

pub fn date(input: &Value, args: &[Value]) -> FilterResult {
if args.len() != 1 {
return Err(FilterError::InvalidArgumentCount(format!("expected 1, {} given", args.len())));
}

let date = match input {
&Value::Str(ref s) => try!(DateTime::parse_from_str(&s, "%d %B %Y %H:%M:%S %z")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So the original liquid has a to_date function that I think is a good idea to implement for us as well https://github.com/Shopify/liquid/blob/master/lib/liquid/utils.rb#L63

However, we don't have to do it in this PR. I'll make a follow-up issue.

.map_err(|e| FilterError::InvalidType(format!("Invalid date format: {}", e)))),
_ => return Err(FilterError::InvalidType("String expected".to_owned())),
};

let format = match args[0] {
Value::Str(ref s) => s,
_ => return Err(InvalidArgument(0, "Str expected".to_owned())),
};

Ok(Value::Str(date.format(format).to_string()))
}

#[cfg(test)]
mod tests {

Expand All @@ -312,6 +333,15 @@ mod tests {
}};
}

macro_rules! failed {
( $a:ident, $b:expr ) => {{
failed!($a, $b, &[])
}};
( $a:ident, $b:expr, $c:expr ) => {{
$a(&$b, $c).unwrap_err()
}};
}

macro_rules! tos {
( $a:expr ) => {{
Str($a.to_owned())
Expand Down Expand Up @@ -528,4 +558,23 @@ mod tests {
assert_eq!(result.unwrap(), tos!("a,1,c"));
}

#[test]
fn unit_date() {
assert_eq!(unit!(date, tos!("13 Jun 2016 02:30:00 +0300"), &[tos!("%Y-%m-%d")]), tos!("2016-06-13"));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add tests that pass in wrong values for the three error conditions in your function? There are some (unfortunately not enough) examples in the tests above.


assert_eq!(failed!(date, Num(0f32), &[tos!("%Y-%m-%d")]),
FilterError::InvalidType("String expected".to_owned()));

assert_eq!(failed!(date, tos!("blah blah blah"), &[tos!("%Y-%m-%d")]),
FilterError::InvalidType("Invalid date format: input contains invalid characters".to_owned()));

assert_eq!(failed!(date, tos!("13 Jun 2016 02:30:00 +0300"), &[Num(0f32)]),
FilterError::InvalidArgument(0, "Str expected".to_owned()));

assert_eq!(failed!(date, tos!("13 Jun 2016 02:30:00 +0300")),
FilterError::InvalidArgumentCount("expected 1, 0 given".to_owned()));

assert_eq!(failed!(date, tos!("13 Jun 2016 02:30:00 +0300"), &[Num(0f32), Num(1f32)]),
FilterError::InvalidArgumentCount("expected 1, 2 given".to_owned()));
}
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
#[macro_use]
extern crate lazy_static;
extern crate regex;
extern crate chrono;

use std::collections::HashMap;
use lexer::Element;
Expand Down
3 changes: 2 additions & 1 deletion src/template.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use Renderable;
use context::Context;
use filters::{size, upcase, downcase, capitalize, minus, plus, times, divided_by, ceil, floor,
round, prepend, append, first, last, pluralize, replace};
round, prepend, append, first, last, pluralize, replace, date};
use filters::split;
use filters::join;
use error::Result;
Expand Down Expand Up @@ -32,6 +32,7 @@ impl Renderable for Template {
context.add_filter("pluralize", Box::new(pluralize));
context.add_filter("split", Box::new(split));
context.add_filter("join", Box::new(join));
context.add_filter("date", Box::new(date));

let mut buf = String::new();
for el in &self.elements {
Expand Down