How to determine from which module a specific function was imported in elixir

此生再无相见时 提交于 2020-01-03 17:03:30

问题


When multiple external modules are included by calling use on some intermediate module, is there an easy way to determine in which module given method is actually defined?

E.g:

defmodule ModuleB do
  def method_b do
  end
end    

defmodule ModuleA do
  # imports ModuleB implicitly
  use SomeModuleImportingModuleB

  def method_a
    # how to determine this is ModuleB.method_b?
    method_b
  end
end

回答1:


I found a solution that works for me, by capturing the function using & and then inspecting it:

def method_a
  IO.inspect &method_b/0 
  # outputs &ModuleB.method_b
  method_b
end



回答2:


Every module defines an __info__ function, you can use it to view functions exported by that module:

IO.inspect ModuleB.__info__(:exports)
# => [method_b: 0, module_info: 0, module_info: 1, __info__: 1]

Please note that when using use the module in question might be injecting code directly into the module being defined and creating functions dynamically - this might cause functions to become available that have not been defined in the used module.



来源:https://stackoverflow.com/questions/32648894/how-to-determine-from-which-module-a-specific-function-was-imported-in-elixir

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!