diff --git a/lib/ecto/ulid.ex b/lib/ecto/ulid.ex index 42d2b07..19635f6 100644 --- a/lib/ecto/ulid.ex +++ b/lib/ecto/ulid.ex @@ -76,6 +76,18 @@ defmodule Ecto.ULID do <> end + @doc """ + Dictates how the type should be treated inside embeds. + By default, the type is sent as itself. Instead of sending it as 26 bytes, + it's being dumped to a string representation which is more useful in embeded schemas. + """ + def embed_as(_), do: :dump + + @doc """ + Checks if two terms are equal. + """ + def equal?(term1, term2), do: term1 == term2 + defp encode(<< b1::3, b2::5, b3::5, b4::5, b5::5, b6::5, b7::5, b8::5, b9::5, b10::5, b11::5, b12::5, b13::5, b14::5, b15::5, b16::5, b17::5, b18::5, b19::5, b20::5, b21::5, b22::5, b23::5, b24::5, b25::5, b26::5>>) do <>) == :error end + + test "embed_as/1 returns :dump" do + ulid = Ecto.ULID.bingenerate() + assert Ecto.ULID.embed_as(ulid) == :dump + end + + test "embedded_dump dumps ULID as binary from schema" do + ulid = Ecto.ULID.generate() + {:ok, decoded} = Ecto.ULID.dump(ulid) + assert Ecto.Type.embedded_dump(Ecto.ULID, ulid, :any_format) == {:ok, decoded} + end + + test "embedded_load loads ULID as string to embeded schema" do + ulid = Ecto.ULID.bingenerate() + {:ok, encoded} = Ecto.ULID.load(ulid) + assert Ecto.Type.embedded_load(Ecto.ULID, ulid, :any_format) == {:ok, encoded} + end + + test "equal?/1 compares correctly two equal string ULIDs" do + ulid = Ecto.ULID.generate() + assert Ecto.ULID.equal?(ulid, ulid) == true + end + + test "equal?/1 compares correctly two different string ULIDs" do + ulid1 = Ecto.ULID.generate() + ulid2 = Ecto.ULID.generate() + assert Ecto.ULID.equal?(ulid1, ulid2) == false + end + + test "equal?/1 compares correctly two equal binary ULIDs" do + ulid = Ecto.ULID.bingenerate() + assert Ecto.ULID.equal?(ulid, ulid) == true + end + + test "equal?/1 compares correctly two different binary ULIDs" do + ulid1 = Ecto.ULID.bingenerate() + ulid2 = Ecto.ULID.bingenerate() + assert Ecto.ULID.equal?(ulid1, ulid2) == false + end end