Skip to content

Commit

Permalink
in helper
Browse files Browse the repository at this point in the history
  • Loading branch information
jrouaix committed Feb 2, 2022
1 parent e133c71 commit fc9dfe1
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 89 deletions.
104 changes: 18 additions & 86 deletions codegenr/src/helpers/equals.rs
Original file line number Diff line number Diff line change
@@ -1,107 +1,39 @@
use super::handlebars_ext::HandlebarsExt;
use handlebars::{HelperDef, Renderable};
use handlebars::HelperDef;

pub const IF_EQUALS_HELPER: &str = "if_equals";
pub const IF_NOT_EQUALS_HELPER: &str = "if_not_equals";
pub const IN_HELPER: &str = "in";

/// Execute template if the first argument is equal to any other argument, otherwise execute the inverse
/// (all arguments are converted to string and case insensitive compared)
/// Returns true if the first argument is equal to any value in the second argument array
/// ```
/// # use codegenr_lib::helpers::*;
/// # use serde_json::json;
/// //assert_eq!(
/// //exec_template(json!({}), r#"{{#if_equals "test" "teSt"}}OK{{else}}{{/if_equals}}"#),
/// //"OK"
/// //);
/// assert_eq!(
/// exec_template(json!({ "a": "42", "b": "42" }), r#"{{#if_equals a ./b }}OK{{else}}{{/if_equals}}"#),
/// "OK"
/// );
/// assert_eq!(
/// exec_template(json!({}), r#"{{#if_equals "test" "NO"}}OK{{else}}NOK{{/if_equals}}"#),
/// exec_template(json!({}), r#"{{#if (in "test" ["NO"])}}OK{{else}}NOK{{/if}}"#),
/// "NOK"
/// );
/// assert_eq!(
/// exec_template(json!({}), r#"{{#if_equals "test" "NO" "NO" "test"}}OK{{else}}NOK{{/if_equals}}"#),
/// exec_template(json!({"array": ["NO","NO","test"]}), r#"{{#if (in "test" array)}}OK{{else}}NOK{{/if}}"#),
/// "OK"
/// );
/// assert_eq!(
/// exec_template(json!({}), r#"{{#if_equals "test" "NO" "NOPE"}}OK{{else}}NOK{{/if_equals}}"#),
/// exec_template(json!({}), r#"{{#if (in "test" (str_to_json "[\"NO\",\"NOPE\"]"))}}OK{{else}}NOK{{/if}}"#),
/// "NOK"
/// );
/// ```
pub struct IfEqualsHelper;
pub struct InHelper;

impl HelperDef for IfEqualsHelper {
fn call<'reg: 'rc, 'rc>(
impl HelperDef for InHelper {
fn call_inner<'reg: 'rc, 'rc>(
&self,
h: &handlebars::Helper<'reg, 'rc>,
handle: &'reg handlebars::Handlebars<'reg>,
ctx: &'rc handlebars::Context,
render_ctx: &mut handlebars::RenderContext<'reg, 'rc>,
out: &mut dyn handlebars::Output,
) -> handlebars::HelperResult {
h.ensure_arguments_count_min(2, IF_EQUALS_HELPER)?;
let value = h.get_param_as_json_or_fail(0, IF_EQUALS_HELPER)?;

// todo: insensitive strings compare (when both strings)
let is_value_found = h.params().iter().skip(1).any(|p| p.value() == value);
let temp = if is_value_found { h.template() } else { h.inverse() };

match temp {
Some(t) => t.render(handle, ctx, render_ctx, out),
None => Ok(()),
}
}
}

/// Execute template if the first argument is not equal to all other arguments, otherwise execute the inverse
/// (all arguments are converted to string and case insensitive compared)
/// ```
/// # use codegenr_lib::helpers::*;
/// # use serde_json::json;
/// //assert_eq!(
/// //exec_template(json!({}), r#"{{#if_not_equals "test" "teSt"}}{{else}}NOK{{/if_not_equals}}"#),
/// //"NOK"
/// //);
/// assert_eq!(
/// exec_template(json!({ "a": "42", "b": "42" }), r#"{{#if_not_equals a ./b }}{{else}}NOK{{/if_not_equals}}"#),
/// "NOK"
/// );
/// assert_eq!(
/// exec_template(json!({}), r#"{{#if_not_equals "test" "NO"}}OK{{else}}NOK{{/if_not_equals}}"#),
/// "OK"
/// );
/// assert_eq!(
/// exec_template(json!({}), r#"{{#if_not_equals "test" "NO" "NO" "test"}}OK{{else}}NOK{{/if_not_equals}}"#),
/// "NOK"
/// );
/// assert_eq!(
/// exec_template(json!({}), r#"{{#if_not_equals "test" "NO" "NOPE"}}OK{{else}}NOK{{/if_not_equals}}"#),
/// "OK"
/// );
/// ```
pub struct IfNotEqualsHelper;

impl HelperDef for IfNotEqualsHelper {
fn call<'reg: 'rc, 'rc>(
&self,
h: &handlebars::Helper<'reg, 'rc>,
handle: &'reg handlebars::Handlebars<'reg>,
ctx: &'rc handlebars::Context,
render_ctx: &mut handlebars::RenderContext<'reg, 'rc>,
out: &mut dyn handlebars::Output,
) -> handlebars::HelperResult {
h.ensure_arguments_count_min(2, IF_NOT_EQUALS_HELPER)?;
let value = h.get_param_as_json_or_fail(0, IF_NOT_EQUALS_HELPER)?;

// todo: insensitive strings compare (when both strings)
let is_value_found = h.params().iter().skip(1).any(|p| p.value() == value);
let temp = if !is_value_found { h.template() } else { h.inverse() };

match temp {
Some(t) => t.render(handle, ctx, render_ctx, out),
None => Ok(()),
}
_: &'reg handlebars::Handlebars<'reg>,
_: &'rc handlebars::Context,
_: &mut handlebars::RenderContext<'reg, 'rc>,
) -> Result<handlebars::ScopedJson<'reg, 'rc>, handlebars::RenderError> {
h.ensure_arguments_count(2, IN_HELPER)?;
let value = h.get_param_as_json_or_fail(0, IN_HELPER)?;
let array = h.get_param_as_array_or_fail(1, IN_HELPER)?;
let contains = array.iter().any(|v| v == value);
Ok(handlebars::ScopedJson::Derived(contains.into()))
}
}
9 changes: 7 additions & 2 deletions codegenr/src/helpers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ pub fn handlebars_stateless_setup(handlebars: &mut Handlebars) {
handlebars.register_helper(DEBUG_CTX, Box::new(DebugCtxHelper));
handlebars.register_helper(IF_EMPTY_HELPER, Box::new(IfEmptyHelper));
handlebars.register_helper(IF_NOT_EMPTY_HELPER, Box::new(IfNotEmptyHelper));
handlebars.register_helper(IF_EQUALS_HELPER, Box::new(IfEqualsHelper));
handlebars.register_helper(IF_NOT_EQUALS_HELPER, Box::new(IfNotEqualsHelper));
handlebars.register_helper(IN_HELPER, Box::new(InHelper));
handlebars.register_helper(HEX, Box::new(Hex));
handlebars.register_helper(TRIM_CHAR_HELPER, Box::new(TrimCharHelper));
handlebars.register_helper(TRIM_CHAR_START_HELPER, Box::new(TrimCharStartHelper));
Expand Down Expand Up @@ -75,10 +74,15 @@ pub fn handlebars_statefull_setup(handlebars: &mut Handlebars, global_params: Ha
handlebars.register_helper(GLOBAL_PARAMETERS_HELPER, Box::new(GlobalParameterHelper::new(global_params)));
}

pub fn handlebars_misc_setup(handlebars: &mut Handlebars) {
handlebars_misc_helpers::register(handlebars);
}

pub fn exec_template(json: serde_json::Value, template: &str) -> String {
let mut h = Handlebars::new();
handlebars_stateless_setup(&mut h);
handlebars_statefull_setup(&mut h, Default::default());
handlebars_misc_setup(&mut h);
h.register_template_string("test", template).expect("Could not register template.");
h.render("test", &json).expect("Template render returned an error.")
}
Expand All @@ -87,6 +91,7 @@ pub fn exec_template_with_global_params(json: serde_json::Value, template: &str,
let mut h = Handlebars::new();
handlebars_stateless_setup(&mut h);
handlebars_statefull_setup(&mut h, global_params);
handlebars_misc_setup(&mut h);
h.register_template_string("test", template).expect("Could not register template.");
h.render("test", &json).expect("Template render returned an error.")
}
2 changes: 1 addition & 1 deletion codegenr/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ fn run_codegenr(
.clone();

helpers::handlebars_statefull_setup(&mut handlebars, options.global_parameters);
handlebars_misc_helpers::register(&mut handlebars);
helpers::handlebars_misc_setup(&mut handlebars);

let rendered = handlebars.render(&main_template_name, &(*json))?;

Expand Down

0 comments on commit fc9dfe1

Please sign in to comment.