-
Notifications
You must be signed in to change notification settings - Fork 82
/
custom_constructor.rs
73 lines (64 loc) · 1.96 KB
/
custom_constructor.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
#![allow(dead_code)]
use derive_builder::Builder;
#[derive(Debug, Clone)]
pub enum ContentType {
Json,
Xml,
}
impl Default for ContentType {
fn default() -> Self {
Self::Json
}
}
#[derive(Debug, Builder)]
#[builder(
custom_constructor,
create_empty = "empty",
build_fn(private, name = "fallible_build")
)]
pub struct ApiClient {
// To make sure `host` and `key` are not changed after creation, tell derive_builder
// to create the fields but not to generate setters.
#[builder(setter(custom))]
host: String,
#[builder(setter(custom))]
key: String,
// uncommenting this field will cause the unit-test below to fail
// baz: String,
#[builder(default)]
content_type: ContentType,
}
impl ApiClient {
pub fn new(host: impl Into<String>, key: impl Into<String>) -> ApiClientBuilder {
ApiClientBuilder {
host: Some(host.into()),
key: Some(key.into()),
..ApiClientBuilder::empty()
}
}
}
impl ApiClientBuilder {
pub fn build(&self) -> ApiClient {
self.fallible_build()
.expect("All required fields were initialized")
}
}
fn main() {
dbg!(ApiClient::new("hello", "world")
.content_type(ContentType::Xml)
.build());
}
#[cfg(test)]
mod tests {
use super::ApiClient;
/// If any required fields are added to ApiClient and ApiClient::new was not updated,
/// the field will be `None` when this "infallible" build method is called, resulting
/// in a panic. Panicking is appropriate here, since the author of the builder promised
/// the caller that it was safe to call new(...) followed immediately by build(), and
/// the builder author is also the person who can correct the coding error by setting
/// a default for the new property or changing the signature of `new`
#[test]
fn api_client_new_collects_all_required_fields() {
ApiClient::new("hello", "world").build();
}
}