如果模块是 3rd-party 和/或已经编译,请参考@Dogbert 提供的答案。
如果拥有该模块,则可以在编译阶段使用@on_definition
钩子收集请求的信息:
defmodule TestInfo do
def on_definition(_env, kind, name, args, guards, body) do
with {:ok, table} <- :dets.open_file(:test_info, type: :set) do
clauses =
case :dets.lookup(table, name) do
{:error, _reason} -> []
[] -> []
list when is_list(list) -> list[name]
end
:dets.insert(table, {name, [{kind, args, guards} | clauses]})
:dets.close(table)
end
end
end
defmodule Test do
@on_definition {TestInfo, :on_definition} # ⇐ THIS
def greet(name) when name == "foo" do
IO.puts("Hello, bar")
end
def greet(name), do: IO.puts("Hello, #{name}")
end
现在您已将所有定义存储在 DETS 中:
{:ok, table} = :dets.open_file(:test_info, type: :set)
:dets.lookup(table, :greet)
#⇒ [
# greet: [
# {:def, [{:name, [line: 10], nil}], []},
# {:def, [{:name, [line: 6], nil}],
# [{:==, [line: 6], [{:name, [line: 6], nil}, "foo"]}]}]
# ]
:dets.close(table)
我使用 DETS 来存储信息,因为它存储在编译阶段,典型用法是在运行时。