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)
你会想要使用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.前缀很重要。如果你不包括它,系统将不知道你在寻找什么。
我建议使用该Module模块。
iex(1)> Module.concat ["Repo"]
Repo
iex(2)> Module.safe_concat ["Repo"]
Repo
Run Code Online (Sandbox Code Playgroud)