Skip to content

Commit

Permalink
feat: add common usage examples of derive_builder
Browse files Browse the repository at this point in the history
  • Loading branch information
okqin committed Jul 9, 2024
1 parent 0ab1674 commit cd15ccc
Show file tree
Hide file tree
Showing 3 changed files with 227 additions and 0 deletions.
147 changes: 147 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }

[dev-dependencies]
axum = { version = "0.7.5", features = ["http2", "query", "tracing"] }
chrono = "0.4.38"
derive_builder = "0.20.0"
rand = "0.8.5"
serde = { version = "1.0.203", features = ["derive"] }
serde_json = "1.0.120"
Expand Down
78 changes: 78 additions & 0 deletions examples/builder.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
use anyhow::Result;
use chrono::{DateTime, Utc};
use derive_builder::Builder;

#[allow(unused)]
#[derive(Debug, Clone)]
enum Sensor {
Temperature,
Pressure,
Humidity,
Lightning,
Vibration,
Smoke,
}

#[allow(unused)]
#[derive(Builder, Debug)]
#[builder(setter(into))]
struct Device {
id: u64,

name: String,

device_type: Sensor,

#[builder(setter(custom))]
create_date: DateTime<Utc>,

#[builder(setter(skip), default = "self.running_time_default()")]
running_time: u64,

#[builder(default, setter(into, strip_option))]
location: Option<String>,

#[builder(default = "true")]
is_active: bool,

#[builder(default = "vec![]", setter(each(name = "data_value")))]
data: Vec<String>,
}

fn main() -> Result<()> {
let device = Device::builder()
.id("29388844402912".parse::<u64>()?)
.name("temperature sensor")
.device_type(Sensor::Temperature)
.create_date("2024-07-01T12:34:56Z")
.data_value("30.3".into())
.data_value("26.8".into())
.build()?;

println!("{:#?}", device);

Ok(())
}

impl Device {
pub fn builder() -> DeviceBuilder {
DeviceBuilder::default()
}
}

impl DeviceBuilder {
pub fn create_date(&mut self, value: &str) -> &mut Self {
self.create_date = value.parse::<DateTime<Utc>>().ok();
self
}

fn running_time_default(&self) -> u64 {
match self.create_date {
Some(date) => {
let time = Utc::now() - date;
time.num_days() as u64
}
None => 0,
}
}
}

0 comments on commit cd15ccc

Please sign in to comment.