Created
October 20, 2016 11:10
-
-
Save arjan/e439cac1289cbb2ea6667641f4a965f0 to your computer and use it in GitHub Desktop.
Elixir function decorator example
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 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