如何在Elixir Tesla中定义函数调用,源代码在哪里?
问题描述:
我正在查看HTTP客户端软件包Tesla的源代码,并试图找到Tesla.get/2函数的源代码,但在这里找不到它,就像其他http方法的函数一样。顺便说一句,在线文档中的'查看源代码'链接也不是。我很困惑,有人可以解释这一点吗?如何在Elixir Tesla中定义函数调用,源代码在哪里?
答
该包使用元编程为每个HTTP动词生成函数。动词的名称定义here
@http_verbs ~w(head get delete trace options post put patch)a
该列表遍历和函数是动态的每个here生成。每个功能的实际主体在generate_api
功能here中定义。所以Tesla.get/2
实际源this:
def unquote(method)(url, body) do
request(method: unquote(method), url: url, body: body)
end
如果替代method
与:get
,你得到的Tesla.get/2
有效的定义:
def get(url, body) do
request(method: :get, url: url, body: body)
end
你可以阅读的编译二郎形式模块的代码也是这样的:
{_, _, bytecode} = :code.get_object_code(Tesla)
{:ok, {_, [{:abstract_code, {_, ac}}]}} = :beam_lib.chunks(bytecode, [:abstract_code])
ac |> :erl_syntax.form_list |> :erl_prettypr.format |> IO.puts
输出是巨大的,但如果你仔细看,你会看到生成所有get/2
条款:
...
get(#{'__struct__' := 'Elixir.Tesla.Client'} = [email protected],
[email protected]) ->
request([email protected], [{method, get}, {url, [email protected]}]);
get([email protected], [email protected]) when erlang:is_function([email protected]) ->
get(#{post => [], pre => [], 'fun' => [email protected],
'__struct__' => 'Elixir.Tesla.Client'},
[email protected]);
get([email protected], [email protected]) when erlang:is_list([email protected]) ->
request([{method, get}, {url, [email protected]}] ++ [email protected]).
...