Last active
September 7, 2016 09:03
-
-
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.
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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).