Skip to content

Instantly share code, notes, and snippets.

@ityonemo
Last active September 23, 2021 20:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ityonemo/3fd313667721d20984bbc2589ac0f3b6 to your computer and use it in GitHub Desktop.
Save ityonemo/3fd313667721d20984bbc2589ac0f3b6 to your computer and use it in GitHub Desktop.
convertible.ex
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