Skip to content

Instantly share code, notes, and snippets.

@Wigny
Created June 28, 2023 04:10
Show Gist options
  • Save Wigny/5d084d45d470eca1213c8205759470f6 to your computer and use it in GitHub Desktop.
Save Wigny/5d084d45d470eca1213c8205759470f6 to your computer and use it in GitHub Desktop.
defmodule DefMaybe do
defmacro defmaybe(fun) do
quote bind_quoted: [fun: Macro.escape(fun, unquote: true)], location: :keep do
{fun_name, fun_args} = Macro.decompose_call(fun)
resource = List.first(fun_args)
action = Keyword.get(opts, :action)
def unquote(:"maybe_#{fun_name}")({:ok, unquote_splicing(fun_args)}) do
{:ok, unquote(fun_name)(unquote_splicing(fun_args))}
end
def unquote(:"maybe_#{fun_name}")(otherwise) do
otherwise
end
end
end
end
defmodule Test do
import DefMaybe
defmaybe foo(bar)
def foo(bar), do: bar
def test do
maybe_foo({:ok, "bar"})
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment