/
tracker_protocol.ex
58 lines (45 loc) · 1.27 KB
/
tracker_protocol.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
53
54
55
56
57
58
defprotocol ExAudit.Tracker do
@moduledoc """
Enables you to influence which fields are tracked. In map_struct, remove or alter any fields
you don't want tracked.
Most of the time, you can just use
```
@derive {ExAudit.Tracker, options}
```
where options is either:
* `except: [:foo, :bar]` to ignore certain fields or
* `only: [:baz, :foobar]` to track only those fields.
"""
@fallback_to_any true
def map_struct(struct)
end
defimpl ExAudit.Tracker, for: Any do
@ignored_fields [:__meta__, :__struct__]
defmacro __deriving__(module, struct, options) do
deriving(module, struct, options)
end
def deriving(module, _struct, options) do
only = options[:only]
except = options[:except]
extractor =
cond do
only ->
quote(do: Map.take(struct, unquote(only)))
except ->
except = @ignored_fields ++ except
quote(do: Map.drop(struct, unquote(except)))
true ->
quote(do: Map.drop(struct, unquote(@ignored_fields)))
end
quote do
defimpl ExAudit.Tracker, for: unquote(module) do
def map_struct(struct) do
unquote(extractor)
end
end
end
end
def map_struct(struct) do
Map.drop(struct, @ignored_fields)
end
end