Skip to content

Commit d341303

Browse files
committed
Add default implementaion for equal? and embed_as
1 parent 63aa134 commit d341303

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

lib/ecto/ulid.ex

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,18 @@ defmodule Ecto.ULID do
7676
<<timestamp::unsigned-size(48), :crypto.strong_rand_bytes(10)::binary>>
7777
end
7878

79+
@doc """
80+
Dictates how the type should be treated inside embeds.
81+
By default, the type is sent as itself. Instead of sending it as 26 bytes,
82+
it's being dumped to a string representation which is more useful in embeded schemas.
83+
"""
84+
def embed_as(_), do: :dump
85+
86+
@doc """
87+
Checks if two terms are equal.
88+
"""
89+
def equal?(term1, term2), do: term1 == term2
90+
7991
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,
8092
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
8193
<<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),

test/ecto/ulid_test.exs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,4 +135,43 @@ defmodule Ecto.ULIDTest do
135135
test "load/1 returns error when data is too long" do
136136
assert Ecto.ULID.load(<<0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0>>) == :error
137137
end
138+
139+
test "embed_as/1 returns :dump" do
140+
ulid = Ecto.ULID.bingenerate()
141+
assert Ecto.ULID.embed_as(ulid) == :dump
142+
end
143+
144+
test "embedded_dump dumps ULID as string to schema" do
145+
ulid = Ecto.ULID.generate()
146+
{:ok, decoded} = Ecto.ULID.dump(ulid)
147+
assert Ecto.Type.embedded_dump(Ecto.ULID, ulid, :any_format) == {:ok, decoded}
148+
end
149+
150+
test "embedded_load loads ULID as binary from embeded schema" do
151+
ulid = Ecto.ULID.bingenerate()
152+
{:ok, encoded} = Ecto.ULID.load(ulid)
153+
assert Ecto.Type.embedded_load(Ecto.ULID, ulid, :any_format) == {:ok, encoded}
154+
end
155+
156+
test "equal?/1 compares correctly two equal string ULIDs" do
157+
ulid = Ecto.ULID.generate()
158+
assert Ecto.ULID.equal?(ulid, ulid) == true
159+
end
160+
161+
test "equal?/1 compares correctly two different string ULIDs" do
162+
ulid1 = Ecto.ULID.generate()
163+
ulid2 = Ecto.ULID.generate()
164+
assert Ecto.ULID.equal?(ulid1, ulid2) == false
165+
end
166+
167+
test "equal?/1 compares correctly two equal binary ULIDs" do
168+
ulid = Ecto.ULID.bingenerate()
169+
assert Ecto.ULID.equal?(ulid, ulid) == true
170+
end
171+
172+
test "equal?/1 compares correctly two different binary ULIDs" do
173+
ulid1 = Ecto.ULID.bingenerate()
174+
ulid2 = Ecto.ULID.bingenerate()
175+
assert Ecto.ULID.equal?(ulid1, ulid2) == false
176+
end
138177
end

0 commit comments

Comments
 (0)