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

Add proc macro to generate functions for the setter pattern automatically #76

Open
LukaOber opened this issue Sep 16, 2024 · 2 comments

Comments

@LukaOber
Copy link
Collaborator

Adding a proc macro that we can derive on the structs could automatically generate most functions for the builder pattern for us.

Currently we have this:

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Chart {
    #[serde(skip_serializing_if = "Vec::is_empty")]
    title: Vec<Title>,

    #[serde(skip_serializing_if = "Option::is_none")]
    tooltip: Option<Tooltip>,
    
   // cut for brevity

And we manually implement the function to set the fields:

pub fn title(mut self, title: Title) -> Self {
    self.title.push(title);
    self
}

pub fn tooltip(mut self, tooltip: Tooltip) -> Self {
    self.tooltip = Some(tooltip);
    self
}

// cut for brevity

With a proc macro we could switch to this:

#[derive(Serialize, CharmingBuilder)]
#[serde(rename_all = "camelCase")]
pub struct Chart {
    #[serde(skip_serializing_if = "Vec::is_empty")]
    title: Vec<Title>,

    #[serde(skip_serializing_if = "Option::is_none")]
    tooltip: Option<Tooltip>,
    
   // cut for brevity

And the derived trait will automatically generate the functions for Vec<T> and Option<T> like this without having to write them manually:

pub fn title(mut self, title: Title) -> Self {
    self.title.push(title);
    self
}

pub fn tooltip(mut self, tooltip: Tooltip) -> Self {
    self.tooltip = Some(tooltip);
    self
}

// cut for brevity

Pros: Would cut down on potential errors and time for adding new fields.

Cons: Slight increase in fresh compilation time.

I think it would be better to use a proc macro to reduce a lot of repetition in the crate and I would also be able to prepare the corresponding PR if you are interested.

@LukaOber
Copy link
Collaborator Author

We should probably use or build on something like derive_setters

@LukaOber LukaOber changed the title Add proc macro to generate functions for the builder pattern automatically Add proc macro to generate functions for the setter pattern automatically Oct 31, 2024
@LukaOber
Copy link
Collaborator Author

I opened up a draft pr in #105. If someone is familiar with proc macros, please feel free to check it out and comment on it.

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

No branches or pull requests

1 participant