Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions lib/ecto/ulid.ex
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,18 @@ defmodule Ecto.ULID do
<<timestamp::unsigned-size(48), :crypto.strong_rand_bytes(10)::binary>>
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
<<e(b1), e(b2), e(b3), e(b4), e(b5), e(b6), e(b7), e(b8), e(b9), e(b10), e(b11), e(b12), e(b13),
Expand Down
39 changes: 39 additions & 0 deletions test/ecto/ulid_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,43 @@ defmodule Ecto.ULIDTest do
test "load/1 returns error when data is too long" do
assert Ecto.ULID.load(<<0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0>>) == :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