查找采用行为的所有模块

Hai*_*ito 4 elixir

是否有可能找到已采用某些行为的每个已加载模块?

我正在构建一个非常简单的聊天Bot,我想制作一些很酷的命令,但要实现这一点,我需要一种方法来实现多个命令,最好不要硬编码.

每个命令都是一个函数,它接受三个参数(message,author,chat_channel_ref)并返回true或false,无论它是否匹配并执行某些操作.

当我浏览Elixir教程时,如果能找到所有采用它们的模块,我会发现可能非常适合我的需求的行为.你以前有没有人这样做过?我还能做什么?我还想过"使用"(在使用中我将执行代码以将当前模块添加到代理所持有的列表中).

bit*_*ker 8

这是我的exrm项目的摘录,它基本上完全是这样的:它找到任何实现插件行为的模块:

  @doc """
  Loads all plugins in all code paths.
  """
  @spec load_all() :: [] | [atom]
  def load_all, do: get_plugins(ReleaseManager.Plugin)

  # Loads all modules that extend a given module in the current code path.
  @spec get_plugins(atom) :: [] | [atom]
  defp get_plugins(plugin_type) when is_atom(plugin_type) do
    available_modules(plugin_type) |> Enum.reduce([], &load_plugin/2)
  end

  defp load_plugin(module, modules) do
    if Code.ensure_loaded?(module), do: [module | modules], else: modules
  end

  defp available_modules(plugin_type) do
    # Ensure the current projects code path is loaded
    Mix.Task.run("loadpaths", [])
    # Fetch all .beam files
    Path.wildcard(Path.join([Mix.Project.build_path, "**/ebin/**/*.beam"]))
    # Parse the BEAM for behaviour implementations
    |> Stream.map(fn path ->
      {:ok, {mod, chunks}} = :beam_lib.chunks('#{path}', [:attributes])
      {mod, get_in(chunks, [:attributes, :behaviour])}
    end)
    # Filter out behaviours we don't care about and duplicates
    |> Stream.filter(fn {_mod, behaviours} -> is_list(behaviours) && plugin_type in behaviours end)
    |> Enum.uniq
    |> Enum.map(fn {module, _} -> module end)
  end
Run Code Online (Sandbox Code Playgroud)