Elixir常量一个字符串来获取模块(String.to_module/1)



我在会话中存储了一些元数据,以便根据字符串访问不同的模块。

有什么办法可以做到这一点吗?

String.to_module("MyApp.Vendor")   #=> MyApp.Vendor
String.to_module("MyApp.Customer") #=> MyApp.Customer

然后最终目标是使用 account_type 按 id 查找结构体,以执行特定于该类型的操作。

account = Repo.get(String.to_module(account_type), account_id)
do_something_with(account)
def do_something_with(%Customer{id: id}) do 
  # yada yada
end
def do_something_with(%Vendor{id: id}) do 
  # something else
end

您将要使用String.to_existing_atom .

iex(5)> a = String.to_existing_atom("Elixir.Enum")
Enum
iex(6)> apply(a, :reverse, [[1, 2, 3]])

请注意,Elixir.前缀很重要。如果您不包括它,系统将不知道您要查找的内容。

我建议使用Module模块。

iex(1)> Module.concat ["Repo"]
Repo
iex(2)> Module.safe_concat ["Repo"]
Repo

最新更新