Skip to content

Instantly share code, notes, and snippets.

@arjan
Created October 20, 2016 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arjan/e439cac1289cbb2ea6667641f4a965f0 to your computer and use it in GitHub Desktop.
Save arjan/e439cac1289cbb2ea6667641f4a965f0 to your computer and use it in GitHub Desktop.
Elixir function decorator example
defmodule DecoratorTest do
defmacro decorate() do
Module.put_attribute(__CALLER__.module, :decorated, :true)
end
defmacro def(fn_call_ast, fn_opts_ast \\ nil) do
mod = __CALLER__.module
{fn_name, _, _} = fn_call_ast
if Module.get_attribute(mod, :decorated) do
IO.puts "Decorate function: #{mod}.#{fn_name}"
end
Module.delete_attribute(mod, :decorated)
quote do
Kernel.def(
unquote(fn_call_ast), unquote(fn_opts_ast))
end
end
defmacro __using__(_) do
quote do
import Kernel, except: [def: 2]
import DecoratorTest, only: [def: 2, decorate: 0]
end
end
end
## usage:
defmodule MyModule do
use DecoratorTest
decorate()
def foo(bar) do
bar + 1
end
def foo2(bar) do
bar + 1
end
end
## output:
# Compiling 1 file (.ex)
# Decorate function: Elixir.MyModule.foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment