Skip to content

Instantly share code, notes, and snippets.

@zampino
Last active July 20, 2022 00:32
Show Gist options
  • Save zampino/f97cd5f31e1db83aca05 to your computer and use it in GitHub Desktop.
Save zampino/f97cd5f31e1db83aca05 to your computer and use it in GitHub Desktop.
Elixir Extending a Struct
defmodule DSL do
defmacro extend_struct struct_mod, keyword do
quote do
defstruct Keyword.merge(Map.to_list(Map.from_struct(unquote(struct_mod).__struct__)), unquote(keyword))
end
end
end
defmodule DSLTest do
use ExUnit.Case
defmodule BaseStruct do
defstruct a: 1, b: "two"
end
defmodule TestStruct do
import DSL
extend_struct BaseStruct, some: "extra", key: "with overrides", b: "three"
end
test "it can merge structures" do
ts = %TestStruct{}
map = Map.from_struct ts
assert map == %{a: 1, b: "three", key: "with overrides", some: "extra"}
end
end
@dwhelan
Copy link

dwhelan commented Jun 11, 2018

Nice!

Could use pipes with the defstruct:

quote bind_quoted: [struct_mod: struct_mod, keyword: keyword] do
  defstruct struct_mod |> Map.from_struct |> Map.to_list |> Keyword.merge(keyword)
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment