elixir 将字符串常量化以获取模块 (String.to_module/1)?

dai*_*no3 3 elixir phoenix-framework

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

有没有办法做到这一点?

String.to_module("MyApp.Vendor")   #=> MyApp.Vendor
String.to_module("MyApp.Customer") #=> MyApp.Customer
Run Code Online (Sandbox Code Playgroud)

然后最终目标是使用account_typeid 查找 Struct 以执行特定于该类型的操作。

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
Run Code Online (Sandbox Code Playgroud)

Jus*_*ood 5

你会想要使用String.to_existing_atom.

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

请注意,Elixir.前缀很重要。如果你不包括它,系统将不知道你在寻找什么。


Ste*_*len 5

我建议使用该Module模块。

iex(1)> Module.concat ["Repo"]
Repo
iex(2)> Module.safe_concat ["Repo"]
Repo
Run Code Online (Sandbox Code Playgroud)

  • 几点@daino3。使用内置库来滚动您自己的库(这里没什么意义),不需要担心您可能会忘记的“Elixir”名称空间,一个可用于附加名称空间(如“Module.concat”)的接口[MyApp.Base,“回购”]`。它是一个方便了解的 API,因此我建议即使在最简单的情况下也使用它。最后,我想让你意识到这一点:) (2认同)