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

feat: Add PostBuild trait #95

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

Techassi
Copy link
Contributor

Fixes #67

This PR adds support for the PostBuild trait, which allows users to perform custom validation when the .build() method is called. The validation runs as the last step of the build method.

An example:

use typed_builder::{PostBuild, TypedBuilder};

#[derive(Debug, PartialEq, TypedBuilder)]
#[builder(postbuild)]
struct Foo {
    x: i32,
    y: i32,
}

impl PostBuild for Foo {
    type Output = Result<Self, String>;

    fn postbuild(self) -> Self::Output {
        if self.x >= 5 {
            return Err("x too high - must be below or 5".into());
        }

        Ok(self)
    }
}

fn main() {
    let foo = Foo::builder().x(1).y(2).build().unwrap();
    assert_eq!(foo, Foo { x: 1, y: 2 });

    // Fails to validate during runtime
    // let foo = Foo::builder().x(5).y(6).build().unwrap();
    // assert_eq!(foo, Foo { x: 5, y: 6 });
}

When the user provides #[builder(postbuild)], the macro won't implement a default PostBuild impl. Instead, the user has to implement this trait manually. This allows user to implement custom validation logic.


Note: Some test cases are commented out, as the initial draft of this feature breaks these test cases. Follow-up commits will fix those issues. As such, the PR is a draft. When the test cases are fixed and the code is polished, it is marked as "Ready to review".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Allow invariant checks in .build()
1 participant