簡體   English   中英

在Elixir Tesla中如何定義方法函數調用,源代碼在哪里?

[英]How are the method function calls defined in Elixir Tesla and where is the source code?

我正在查看HTTP客戶端程序包Tesla的源代碼,並試圖找到Tesla.get / 2函數的源代碼,但我在這里找不到它,就像其他http方法的函數一樣。 順便說一句,在線文檔中的“查看源代碼”鏈接也不能。 我感到困惑,有人可以解釋嗎?

該軟件包正在使用元編程為每個HTTP動詞生成函數。 動詞的名稱在這里定義

@http_verbs ~w(head get delete trace options post put patch)a

這個列表遍歷和功能對於動態生成的每一個在這里 每個函數的實際主體在此處的 generate_api函數中定義。 所以實際的源Tesla.get/2這樣

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

您可以閱讀模塊代碼的編譯后的Erlang形式,如下所示:

{_, _, 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'} = _@1,
    _@2) ->
    request(_@1, [{method, get}, {url, _@2}]);
get(_@1, _@2) when erlang:is_function(_@1) ->
    get(#{post => [], pre => [], 'fun' => _@1,
      '__struct__' => 'Elixir.Tesla.Client'},
    _@2);
get(_@1, _@2) when erlang:is_list(_@2) ->
    request([{method, get}, {url, _@1}] ++ _@2).

...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM