Skip to content

Instantly share code, notes, and snippets.

@zhulinpinyu
Forked from zampino/struct_extension.ex
Created October 17, 2019 06:18
Show Gist options
  • Save zhulinpinyu/ac966f519d3f29a21ff694a6b0880d62 to your computer and use it in GitHub Desktop.
Save zhulinpinyu/ac966f519d3f29a21ff694a6b0880d62 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment