Skip to content

Make ex_constructor a TypedStruct plugin #2

@ejpcmac

Description

@ejpcmac

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions