Skip to content

Commit fda7c19

Browse files
authored
Convert id attribute macro to Ash extension (#83)
1 parent 79efb33 commit fda7c19

2 files changed

Lines changed: 27 additions & 7 deletions

File tree

lib/geo/geography/country.ex

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ defmodule Geo.Geography.Country do
22
use Ash.Resource,
33
otp_app: :geo,
44
domain: Geo.Geography,
5-
data_layer: AshPostgres.DataLayer
5+
data_layer: AshPostgres.DataLayer,
6+
extensions: [Geo.Resources.Attributes.Id]
67

78
# === Attributes ===
8-
use Geo.Resources.Attributes.Id
99
use Geo.Resources.Attributes.Name, allow_nil?: false, unique?: true
1010
use Geo.Resources.Attributes.Slug, allow_nil?: false, unique?: true
1111
use Geo.Resources.Attributes.Timestamps

lib/geo/resources/attributes/id.ex

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,32 @@
11
defmodule Geo.Resources.Attributes.Id do
22
@moduledoc """
3+
An Ash extension that adds a UUID v7 primary key attribute to a resource.
34
"""
45

5-
defmacro __using__(_opts) do
6-
quote do
7-
attributes do
8-
uuid_v7_primary_key :id
9-
end
6+
use Spark.Dsl.Extension,
7+
transformers: [
8+
__MODULE__.Transformer
9+
]
10+
11+
defmodule Transformer do
12+
@moduledoc false
13+
use Spark.Dsl.Transformer
14+
15+
def before?(Ash.Resource.Transformers.BelongsToAttribute), do: true
16+
def before?(_), do: false
17+
18+
def transform(dsl_state) do
19+
attribute = %Ash.Resource.Attribute{
20+
name: :id,
21+
type: :uuid_v7,
22+
allow_nil?: false,
23+
writable?: false,
24+
public?: true,
25+
primary_key?: true,
26+
default: &Ash.UUIDv7.generate/0
27+
}
28+
29+
{:ok, Spark.Dsl.Transformer.add_entity(dsl_state, [:attributes], attribute)}
1030
end
1131
end
1232
end

0 commit comments

Comments
 (0)