/typed_struct_ecto_changeset

Plugin for typed struct to be used with ecto changeset

Primary LanguageElixir

TypedStructEctoChangeset

A plugin to enable basic "embeds" Ecto.cast support to the module created by the containing TypedStruct macro.

Example

If this module is defined:

defmodule TypedStructModule do
  use TypedStruct

  typedstruct do
    plugin TypedStructEctoChangeset

    field :age, integer()
    field :name, String.t()
  end
end

Then we can:

  iex> Ecto.Changeset.cast(%TypedStructModule{}, %{"age" => 23, "name" => "John Doe"}, [:age, :name])
  %Ecto.Changeset{}

Limitations

More database-centric fields such as assoc are not yet supported

Example use cases of this plugin

Try the macro out in real time without having to install or write any of your own code.
All you need is a running instance of Livebook

Run in Livebook

Installation

Because this plugin supports the interface defined by the TypedStruct macro, installation assumes you've already added that dependency.

While you can use the original typed_struct library, it seems to no longer be maintained. However, there is a fork here that is quite active.

If available in Hex, the package can be installed by adding typed_struct_ecto_changeset to your list of dependencies in mix.exs:

def deps do
  [
    # Choose either of the following `TypedStruct` libraries
    # The original TypedStruct library
    {:typed_struct, "~> 0.3.0"},
      
    # Or the newer forked TypedStruct library
    {:typedstruct, "~> 0.5.2"},

    # And add this library  
    {:typed_struct_ecto_changeset, "~> 1.0.0"}
  ]
end

Documentation can be generated with ExDoc and published on HexDocs. Once published, the docs can be found at https://hexdocs.pm/typed_struct_ecto_changeset.