Casting Sugar - Announcing EctoMorph, a lib to help casting between structs for Ecto

Ecto is great, we use it for validations. But validating different embeds can quickly get confusing, and there are some ways I found it a bit cumbersome.

I’ve created a lib to help add some sugar to what Ecto does, we’ve been using it in prod and it has been going well so far. Some examples, say you have a schema like this:

defmodule Embed do
  use Ecto.Schema

  embedded_schema do
    field(:bar, :string)
  end
end

defmodule Test do
  use Ecto.Schema

  embedded_schema do
    field(:thing, :string)
    embeds_one(:embed, Embed)
  end
end

Usually you would have to do this:

Ecto.Changeset.cast(%Test{}, %{"thing" => "foo", "embed" => %{"bar"=> "baz"}}, [:thing])
|> Ecto.Changeset.cast_embed(:embed)

With EctoMorph you can do this:

EctoMorph.to_struct(%{"thing" => "foo", "embed" => %{"bar"=> "baz"}}, Test)

I would love feedback on whether people think this is useful, or feature requests!

Repo: https://github.com/Adzz/ecto_morph
I went into more detail here: https://medium.com/@ItizAdz/ecto-cast-ing-sugar-31bddbc62cd7

2 Likes

The Medium post mentions: “This is fine if you have defined those functions, but less good if you don’t want to put a changeset function on the schema.” as why you’d want this library.

But I’m not at all clear why defining Test.changeset and Embed.changeset here is undesirable. The code in those functions is tightly coupled to the schema’s field names, so it makes sense to keep it in the same module.

Yea fair point. I suppose a possible counter point is, imagine if you wanted multiple changeset functions for a schema, say to validate it differently depending on the action a user is taking. I think keeping the schema as a very thin definition is nice, similar to how in rails you might want to keep your models thin.

There is some coupling, I think a changeset function and the schema definition have different concerns. Also the coupling is reduced if the fields referenced in the schema are referenced dynamically, as they are in EctoMorph.