Skip to content

Instantly share code, notes, and snippets.

@henrik
Created December 31, 2015 16:43
Show Gist options
  • Save henrik/68f136f9916165e0defb to your computer and use it in GitHub Desktop.
Save henrik/68f136f9916165e0defb to your computer and use it in GitHub Desktop.
Example of using real guard clauses in your own code with Elixir macros. Inspired by `plug :foo when action in [:create, :update]`. Also see https://gist.github.com/henrik/d21251bcf5d569e16ca9 for "fake" guard clauses that allow any condition/function to be used.
defmodule Lab do
defmacro say({:when, _, [message, condition]}) do
{result, _} = Code.eval_quoted(quote do
case true do
true when unquote(condition) -> true
true -> false
end
end)
if result do
quote do: IO.puts unquote(message)
end
end
end
defmodule Run do
import Lab
def run do
say "won't happen" when 1 > 2
say "hello" when 2 > 1
#say "not valid as a guard clause" when String.include?("hej", "ho")
end
end
Run.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment