Skip to content

Instantly share code, notes, and snippets.

@phuochau
Created September 11, 2020 07:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phuochau/e1497ebff90bf52266470d0f352d5553 to your computer and use it in GitHub Desktop.
Save phuochau/e1497ebff90bf52266470d0f352d5553 to your computer and use it in GitHub Desktop.
Create dynamic function with Elixir Macro
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