spin_templates/
filters.rs

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
// liquid_derive::FilterReflection violates this lint
#![allow(clippy::box_default)]

use heck::{ToKebabCase, ToSnakeCase, ToUpperCamelCase};
use liquid_core::{Filter, ParseFilter, Runtime, ValueView};
use liquid_derive::FilterReflection;

// Filters that are added to the Liquid parser and allow templates to specify
// transformations of input strings

// ADDING A FILTER HERE IS NOT ENOUGH.  You must also:
//
// * Register it with the template ParserBuilder in `Run::template_parser`.
//   Otherwise Liquid won't know about it.
// * Add a test using the registration name to `test_filters` in run.rs.
//   This ensures that the name->parser->filter chain is hooked up correctly.

#[derive(Clone, ParseFilter, FilterReflection)]
#[filter(
    name = "kebab_case",
    description = "Change text to kebab-case.",
    parsed(KebabCaseFilter)
)]
pub(crate) struct KebabCaseFilterParser;

#[derive(Debug, Default, liquid_derive::Display_filter)]
#[name = "kebab_case"]
struct KebabCaseFilter;

impl Filter for KebabCaseFilter {
    fn evaluate(
        &self,
        input: &dyn ValueView,
        _runtime: &dyn Runtime,
    ) -> Result<liquid_core::model::Value, liquid_core::error::Error> {
        let input = input
            .as_scalar()
            .ok_or_else(|| liquid_core::error::Error::with_msg("String expected"))?;

        let input = input.into_string().to_string().to_kebab_case();
        Ok(liquid_core::model::Value::scalar(input))
    }
}

#[derive(Clone, liquid_derive::ParseFilter, liquid_derive::FilterReflection)]
#[filter(
    name = "pascal_case",
    description = "Change text to PascalCase.",
    parsed(PascalCaseFilter)
)]
pub(crate) struct PascalCaseFilterParser;

#[derive(Debug, Default, liquid_derive::Display_filter)]
#[name = "pascal_case"]
struct PascalCaseFilter;

impl Filter for PascalCaseFilter {
    fn evaluate(
        &self,
        input: &dyn ValueView,
        _runtime: &dyn Runtime,
    ) -> Result<liquid::model::Value, liquid_core::error::Error> {
        let input = input
            .as_scalar()
            .ok_or_else(|| liquid_core::error::Error::with_msg("String expected"))?;

        let input = input.into_string().to_string().to_upper_camel_case();
        Ok(liquid::model::Value::scalar(input))
    }
}

#[derive(Clone, liquid_derive::ParseFilter, liquid_derive::FilterReflection)]
#[filter(
    name = "snake_case",
    description = "Change text to snake_case.",
    parsed(SnakeCaseFilter)
)]
pub(crate) struct SnakeCaseFilterParser;

#[derive(Debug, Default, liquid_derive::Display_filter)]
#[name = "snake_case"]
struct SnakeCaseFilter;

impl Filter for SnakeCaseFilter {
    fn evaluate(
        &self,
        input: &dyn ValueView,
        _runtime: &dyn Runtime,
    ) -> Result<liquid::model::Value, liquid_core::error::Error> {
        let input = input
            .as_scalar()
            .ok_or_else(|| liquid_core::error::Error::with_msg("String expected"))?;

        let input = input.into_string().to_string().to_snake_case();
        Ok(input.to_value())
    }
}

#[derive(Clone, liquid_derive::ParseFilter, liquid_derive::FilterReflection)]
#[filter(
    name = "http_wildcard",
    description = "Add Spin HTTP wildcard suffix (/...) if needed.",
    parsed(HttpWildcardFilter)
)]
pub(crate) struct HttpWildcardFilterParser;

#[derive(Debug, Default, liquid_derive::Display_filter)]
#[name = "http_wildcard"]
struct HttpWildcardFilter;

impl Filter for HttpWildcardFilter {
    fn evaluate(
        &self,
        input: &dyn ValueView,
        _runtime: &dyn Runtime,
    ) -> Result<liquid::model::Value, liquid_core::error::Error> {
        let input = input
            .as_scalar()
            .ok_or_else(|| liquid_core::error::Error::with_msg("String expected"))?;

        let route = input.into_string().to_string();
        let wildcard_route = if route.ends_with("/...") {
            route
        } else if route.ends_with('/') {
            format!("{route}...")
        } else {
            format!("{route}/...")
        };

        Ok(wildcard_route.to_value())
    }
}

#[derive(Clone, ParseFilter, FilterReflection)]
#[filter(
    name = "dotted_pascal_case",
    description = "Change text to Dotted.Pascal.Case.",
    parsed(DottedPascalCaseFilter)
)]
pub(crate) struct DottedPascalCaseFilterParser;

#[derive(Debug, Default, liquid_derive::Display_filter)]
#[name = "dotted_pascal_case"]
struct DottedPascalCaseFilter;

impl Filter for DottedPascalCaseFilter {
    fn evaluate(
        &self,
        input: &dyn ValueView,
        _runtime: &dyn Runtime,
    ) -> Result<liquid_core::model::Value, liquid_core::error::Error> {
        let input = input
            .as_scalar()
            .ok_or_else(|| liquid_core::error::Error::with_msg("String expected"))?;

        let input = input.into_string().to_string();

        let result = input
            .split('.')
            .map(|s| s.to_upper_camel_case())
            .collect::<Vec<_>>()
            .join(".");

        Ok(result.to_value())
    }
}

#[cfg(test)]
mod test {
    use liquid_core::{Filter, ValueView};

    // Just to save cluttering the tests with ceremonial bits
    fn dotted_pascal(input: &str) -> String {
        let filter = super::DottedPascalCaseFilter;
        let runtime = liquid_core::runtime::RuntimeBuilder::new().build();
        filter
            .evaluate(&input.to_value(), &runtime)
            .map(|v| v.into_scalar().unwrap().into_string().to_string())
            .unwrap()
    }

    #[test]
    fn test_dotted_pascal_case() {
        assert_eq!("Fermyon.PetStore", dotted_pascal("Fermyon.PetStore"));
        assert_eq!("FermyonPetStore", dotted_pascal("fermyon-pet-store"));
        assert_eq!("FermyonPetStore", dotted_pascal("fermyon_pet_store"));
        assert_eq!("Fermyon.PetStore", dotted_pascal("fermyon.pet-store"));
        assert_eq!("Fermyon.PetStore", dotted_pascal("fermyon.pet_store"));
        assert_eq!("FermyonPetStore", dotted_pascal("fermyon pet store"));
    }
}