Skip to content

Commit

Permalink
Restore behaviour of custom fns
Browse files Browse the repository at this point in the history
Fixes #310
  • Loading branch information
Keats committed Mar 18, 2024
1 parent 9868902 commit 3f31ff2
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 9 deletions.
5 changes: 4 additions & 1 deletion validator_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,11 +182,14 @@ impl ToTokens for ValidateField {
// Custom validation
let mut custom = quote!();
for c in &self.custom {
let tokens = custom_tokens(c.clone(), &field_name, &field_name_str);
let tokens = custom_tokens(c.clone(), &actual_field, &field_name_str);
custom = quote!(
#tokens
);
}
if !self.custom.is_empty() {
custom = wrapper_closure(custom);
}

let nested = if let Some(n) = self.nested {
if n {
Expand Down
11 changes: 5 additions & 6 deletions validator_derive/src/tokens/custom.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
use quote::quote;
use syn::Ident;

use crate::types::Custom;
use crate::utils::quote_message;

pub fn custom_tokens(
custom: Custom,
field_name: &Ident,
field_name: &proc_macro2::TokenStream,
field_name_str: &str,
) -> proc_macro2::TokenStream {
let fn_call = custom.function.unwrap();

let args = if let Some(arg) = custom.use_context {
if arg {
quote!(&self.#field_name, args)
quote!(&#field_name, args)
} else {
quote!(&self.#field_name)
quote!(&#field_name)
}
} else {
quote!(&self.#field_name)
quote!(&#field_name)
};

let message = quote_message(custom.message);
Expand All @@ -37,7 +36,7 @@ pub fn custom_tokens(
::std::result::Result::Err(mut err) => {
#code
#message
err.add_param(::std::borrow::Cow::from("value"), &self.#field_name);
err.add_param(::std::borrow::Cow::from("value"), &#field_name);
errors.add(#field_name_str, err);
}
}
Expand Down
4 changes: 2 additions & 2 deletions validator_derive_tests/tests/complex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ fn test_can_validate_option_fields_with_lifetime() {
custom: Option<&'a str>,
}

fn check_str(_: &Option<&str>) -> Result<(), ValidationError> {
fn check_str(_: &&str) -> Result<(), ValidationError> {
Ok(())
}

Expand Down Expand Up @@ -145,7 +145,7 @@ fn test_can_validate_option_fields_without_lifetime() {
custom: Option<String>,
}

fn check_str(_: &Option<String>) -> Result<(), ValidationError> {
fn check_str(_: &String) -> Result<(), ValidationError> {
Ok(())
}

Expand Down

0 comments on commit 3f31ff2

Please sign in to comment.