[−][src]Derive Macro domain_derive::ValueSetup
#[derive(ValueSetup)]
The ValueSetup
derive macro can be used to setup as much boilerplate as possible
for your choosen value object. It checks some preconditions:
- You are applying this to a struct.
- Your struct has a single field called
value
of any type that is clonable.
Once you've used this macro, you will still need to implement the ValueObject
trait,
but you will not have to implement TryFrom
(or create the validation error for TryFrom
, this
is handled by the macro), or implement PartialEq
or Clone
.
In case you need to use the validation error elsewhere, the created validation error will be the
name of your struct with ValidationError appended. For example, if you have an Email
struct,
then the generated validation error will be called EmailValidationError
.
ⓘThis code runs with edition 2018
#[macro_use] extern crate domain_derive; use domain_patterns::ValueObject; use regex::Regex; #[derive(ValueSetup)] pub struct Email { pub value: String, } impl ValueObject<String> for Email { // This error would be the root error for the crate, using failure most likely. type ValueError = Error; fn validate(value: &String) -> Result<(), Self::ValueError> { let email_rx = Regex::new( r"^(?i)[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$" ).unwrap(); if !email_rx.is_match(value) { return Err(EmailValidationError) } Ok(()) } fn value(&self) -> &String { return &self.value; } }