Created
September 11, 2020 07:16
-
-
Save phuochau/e1497ebff90bf52266470d0f352d5553 to your computer and use it in GitHub Desktop.
Create dynamic function with Elixir Macro
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 MyMacro do | |
defmacro create_some_function_by_number(name, num, do: block) do | |
params = | |
for n <- 1..num do | |
{"id#{n}", Macro.var(:"id#{n}", nil)} | |
end | |
# We can't call Macro.escape because it is for escaping values. | |
# In this case, we have a mixture of values "id#{n}" and | |
# expressions "Macro.var(...)", so we build the map AST by hand. | |
pattern = {:%{}, [], params} | |
conn = | |
Macro.var(:conn, nil) | |
quote do | |
def unquote(:"#{name}")(unquote(conn), unquote(pattern)) do | |
unquote(block) | |
end | |
end | |
end | |
end | |
defmodule MyAppWeb.PageController do | |
use MyAppWeb, :controller | |
import MyMacro | |
create_some_function_by_number :index, 1 do | |
render(conn, "index.html") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment