Created
April 10, 2020 09:43
-
-
Save garthk/4dce42ffa457be1dbfd1bfb5a4024526 to your computer and use it in GitHub Desktop.
Automatic record macro for Elixir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule AutoRecords do | |
defmacro __using__(_opts) do | |
quote do | |
require OpenTelemetry.Records.Auto | |
import OpenTelemetry.Records.Auto, only: [auto_record: 2] | |
end | |
end | |
defmacro auto_record(name, from_lib) do | |
quote do | |
require Record | |
@structfields Record.extract(unquote(name), from_lib: unquote(from_lib)) | |
Record.defrecordp(unquote(name), @structfields) | |
defstruct @structfields | |
@spec from(record(unquote(name))) :: %__MODULE__{} | |
def from(rec) when Record.is_record(rec, unquote(name)) do | |
fields = unquote(name)(rec) | |
struct!(__MODULE__, fields) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment