Skip to content

Instantly share code, notes, and snippets.

@mprymek
Last active August 29, 2015 14:19
Show Gist options
  • Save mprymek/73f878e103f60d6d89e2 to your computer and use it in GitHub Desktop.
Save mprymek/73f878e103f60d6d89e2 to your computer and use it in GitHub Desktop.
Elimination of a boilerplate code using macros in Elixir.
###############################################################################
# Elimination of a boilerplate code using macros in Elixir.
#
# See SO question
# http://stackoverflow.com/questions/29573944/elixir-generating-catch-all-function-calls
#
# Run with:
#
# $ elixir catchall.exs
# Fun1: handled by user code
# Fun1: handled by catchall
# Fun2: handled by user code
# Fun2: handled by catchall
###############################################################################
# This is a "library code" where boilerplate code helpers are implemented
defmodule FunBase do
defmacro __using__(_) do
quote do
import FunBase, only: [fun1_catchall: 0, fun2_catchall: 0]
end
end
defmacro fun1_catchall do
quote do
def fun1(_,_), do: IO.puts("Fun1: handled by catchall")
end
end
defmacro fun2_catchall do
quote do
def fun2(_,_), do: IO.puts("Fun2: handled by catchall")
end
end
end
###############################################################################
# This is a "user code" with minimum of the boilerplate but still explicit catchall.
defmodule FunImpl do
use FunBase
def fun1(1,2), do: IO.puts("Fun1: handled by user code")
# Instead of a boilerplate code, you use just this one line.
# Of course it must be after all user fun1(...,...)s
fun1_catchall
def fun2(1,2), do: IO.puts("Fun2: handled by user code")
# instead of a boilerplate code, you use just this one line
fun2_catchall
end
FunImpl.fun1(1,2)
FunImpl.fun1(3,4)
FunImpl.fun2(1,2)
FunImpl.fun2(3,4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment