3
我的模块中有三个相同的方法,它们(几乎)完全相同。我不是重复函数定义,而是试图定义它们来保持代码最小化和相同。Elixir - 通过元编程定义模块中的函数
到目前为止,我使用Code.eval_string
已经试过:
defmodule MyModule do
Enum.each ~w(method1 method2 method3), fn method ->
@method method
Code.eval_string """
def #{@method}(map) when is_map(map) do
do_map_stuff(:#{@method}, map)
end
def #{@method}(arg) do
do_other_stuff(:#{@method}, arg)
end
"""
end
## Other Methods
end
但是,这将引发ArgumentError
:
Compiling 1 file (.ex)
** (ArgumentError) cannot invoke def/2 outside module
(elixir) lib/kernel.ex:4297: Kernel.assert_module_scope/3
(elixir) lib/kernel.ex:3299: Kernel.define/4
(elixir) expanding macro: Kernel.def/2
nofile:1: (file)
我认为报价/引文结束可能是要走的路,但我不完全确定如何使用它们(我已经阅读了Elixir网站上的Meta Guide)。
我更新它使用原子而不是字符串,它更适合我的情况(也看起来更清洁和可读!) – Sheharyar