Skip to content

Instantly share code, notes, and snippets.

@henrik
Last active September 7, 2016 09:03
Show Gist options
  • Save henrik/d21251bcf5d569e16ca9 to your computer and use it in GitHub Desktop.
Save henrik/d21251bcf5d569e16ca9 to your computer and use it in GitHub Desktop.
Example of using "guard clauses" in your own code with Elixir macros. Inspired by `plug :foo when action in [:create, :update]`. This implementation accepts any types of conditions, not just the subset allowed in actual guard clauses. But also see https://gist.github.com/henrik/68f136f9916165e0defb for an implementation with real guard clauses.
defmodule Lab do
defmacro say({:when, _, [message, condition]}) do
{result, _} = Code.eval_quoted(condition)
if result do
quote do
IO.puts unquote(message)
end
end
end
end
defmodule Run do
import Lab
def run do
say "won't happen" when 1 > 2
say "hello" when 2 > 1
end
end
Run.run
@henrik
Copy link
Author

henrik commented Dec 31, 2015

The Plug implementation can be found hereabouts: https://github.com/elixir-lang/plug/blob/8dc8b4052a3bf32f7a75b0be89283a074c038088/lib/plug/builder.ex#L247 It uses real guard clauses via macros (meaning e.g. you're limited to certain functions).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment