Last active
July 20, 2022 00:32
-
-
Save zampino/f97cd5f31e1db83aca05 to your computer and use it in GitHub Desktop.
Elixir Extending a Struct
This file contains 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 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice!
Could use pipes with the
defstruct
: