EctoMorph
EctoMorph morphs your Ecto capabilities into the s t r a t o s p h e r e !
Usually you have to do something 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
Ecto.Changeset.cast(%Test{}, %{"thing" => "foo", "embed" => %{"bar"=> "baz"}}, [:thing])
|> Ecto.Changeset.cast_embed(:embed)Now we can do this:
EctoMorph.to_struct(%{"thing" => "foo", "embed" => %{"bar"=> "baz"}}, Test)Or something like this:
with {:ok, %{status: 200, body: body}} <- HTTPoison.get("mygreatapi.co.uk") do
Jason.decode!(body)
|> EctoMorph.to_struct(User)
endWe can also whitelist fields to cast / update:
EctoMorph.to_struct(%{"thing" => "foo", "embed" => %{"bar"=> "baz"}}, Test, [:thing])
EctoMorph.to_struct(%{"thing" => "foo", "embed" => %{"bar"=> "baz"}}, Test, [:thing, embed: [:bar]])Other abilities include creating a map from an ecto struct, dropping optional fields if you decide to:
EctoMorph.map_from_struct(%Test{})
%Test{foo: "bar", updated_at: ~N[2000-01-01 23:00:07], inserted_at: ~N[2000-01-01 23:00:07], id: 10}
EctoMorph.map_from_struct(%Test{}, [:exclude_timestamps])
%Test{foo: "bar", id: 10}
EctoMorph.map_from_struct(%Test{}, [:exclude_timestamps, :exclude_id])
%Test{foo: "bar"}and being able to filter some data by the fields in the given schema:
defmodule Test do
use Ecto.Schema
embedded_schema do
field(:random, :string)
end
end
EctoMorph.filter_by_schema_fields(%{"random" => "data", "more" => "fields"}, Test)
%{"random" => "data"}Check out the docs folder for more examples, table of contents below:
Installation
available in Hex, the package can be installed
by adding ecto_morph to your list of dependencies in mix.exs:
def deps do
[
{:ecto_morph, "~> 0.1.9"}
]
endDocumentation can be generated with ExDoc and published on HexDocs. Once published, the docs can be found at https://hexdocs.pm/ecto_morph.