-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
timestamps.ex
52 lines (43 loc) · 1.43 KB
/
timestamps.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
defmodule Ecto.Model.Timestamps do
@moduledoc """
Automatically manage timestamps.
If the user calls `Ecto.Schema.timestamps/0` in their schema, the
model will automatically set callbacks based on the schema information
to update the configured `:inserted_at` and `:updated_at` fields
according to the given type.
"""
defmacro __using__(_) do
quote do
@before_compile Ecto.Model.Timestamps
end
end
import Ecto.Changeset
@doc """
Puts a timestamp in the changeset with the given field and type.
"""
def put_timestamp(changeset, field, type) do
if get_change changeset, field do
changeset
else
put_change changeset, field, Ecto.Type.load!(type, :erlang.universaltime)
end
end
defmacro __before_compile__(env) do
timestamps = Module.get_attribute(env.module, :timestamps)
if timestamps do
type = timestamps[:type]
inserted_at = if field = Keyword.fetch!(timestamps, :inserted_at) do
quote do
before_insert Ecto.Model.Timestamps, :put_timestamp, [unquote(field), unquote(type)]
end
end
updated_at = if field = Keyword.fetch!(timestamps, :updated_at) do
quote do
before_insert Ecto.Model.Timestamps, :put_timestamp, [unquote(field), unquote(type)]
before_update Ecto.Model.Timestamps, :put_timestamp, [unquote(field), unquote(type)]
end
end
{inserted_at, updated_at}
end
end
end