-
-
Save zhulinpinyu/ac966f519d3f29a21ff694a6b0880d62 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