Created
December 31, 2015 16:43
-
-
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.
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(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