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

Make ex_constructor a TypedStruct plugin #2

Open
ejpcmac opened this issue Jun 9, 2020 · 2 comments
Open

Make ex_constructor a TypedStruct plugin #2

ejpcmac opened this issue Jun 9, 2020 · 2 comments

Comments

@ejpcmac
Copy link

ejpcmac commented Jun 9, 2020

Since upstream TypedStruct 0.2.0 now supports plugins, Contructor could be a plugin. This way, it would be composable with other TypedStruct plugins.

The API would look like:

defmodule ConstructorExampleUser do
  use TypedStruct

  # Use the “standard” typedstruct macro.
  typedstruct do
    plugin Constructor # Register Constructor as a plugin. Code can be injected here.
    plugin TypedStructLens # Let’s say we also want to generate lenses.

    field :id, integer(), constructor: &is_integer/1, enforce: true
    field :role,  :user | :admin, constructor: &is_valid_role/1, enforce: true
    field :first_name, String.t(), default: "", constructor: &is_string/1
    field :last_name, String.t(), default: "", constructor: &is_string/1
  end

  def is_valid_role(value) do
    case value do
      :admin -> {:ok, value}
      :user -> {:ok, value}
      _ -> {:error, "invalid role!"}
    end
  end
end
@uberbrodt
Copy link
Owner

@ejpcmac Thanks! Sorry, lost track of this for a bit, but I think this should be simple enough to do.

@ejpcmac
Copy link
Author

ejpcmac commented Apr 13, 2021

No problem, Open Source on your spare time shouldn’t be a pressure :)

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

2 participants