Last active
September 23, 2021 20:35
-
-
Save ityonemo/3fd313667721d20984bbc2589ac0f3b6 to your computer and use it in GitHub Desktop.
convertible.ex
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
defprotocol Convertible do | |
def convert(a, target_struct) | |
end | |
defmodule ConversionBoilerplate do | |
defmacro __using__() do | |
quote do | |
def convert(a, to: struct_module) do | |
# maybe do some asserts here | |
module = Module.concat(__MODULE__, struct_module) | |
if function_exported?(module, :convert, 1) do | |
module.convert(a) | |
else | |
raise "arglebargle" | |
end | |
end | |
end | |
end | |
defmacro defconvertible(module) do | |
quote do | |
defimpl Convertible, for: unquote(module) do | |
use ConversionBoilerplate | |
end | |
end | |
end | |
end | |
import ConversionBoilerplate | |
defconvertible A | |
defmodule A.B do | |
def convert(a) do | |
... | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment